Not*_*bad 2 javascript vue.js vue-component vuejs2
我一直在阅读vue文档并开始编写一些代码来测试我的知识.我曾尝试编写一个在安装时设置数据成员的组件,但似乎没有按预期工作.组件数据成员"profiles"始终为空.我的直觉说它可能是范围但不确定:
Vue.component('profile-grid',
{
template: '<section> {{profiles}} </section>',
//Data es la parte privada del documento. Props la parte publica que se deberia de pasar desde la instancia Vue
data: () =>
{
return {
profiles: []
};
},
methods:
{
},
created: () =>
{
//console.log("I was just created")
},
mounted: () =>
{
//console.log("I was just mounted")
this.profiles = ['1', '2', '3'];
}
})
//Vue instance
new Vue(
{
el:'main',
data:
{
},
methods:
{
},
mounted: () =>
{
}
});
Run Code Online (Sandbox Code Playgroud)
HTML页面
//HTML Page
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
<body>
<main>
<profile-grid></profile-grid>
</main>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="main.js"></script>
</html>
Run Code Online (Sandbox Code Playgroud)
有人知道发生了什么吗?
提前致谢.
不要将 Vue挂钩,方法等声明为箭头函数.this
从父上下文使用箭头函数.
箭头功能没有自己的功能; 使用封闭执行上下文的this值.
您应该使用方法定义语法或函数声明来this
作为Vue实例使用:
mounted: function() {
//do something
}
Run Code Online (Sandbox Code Playgroud)
要么
mounted() {
//do something
}
Run Code Online (Sandbox Code Playgroud)
请参阅本节底部的Vue docs notice.
您偶然发现了 vuejs 反应性警告之一。基本上,您正在以 Vuejs 无法响应的方式替换原始配置文件,因此它没有得到更新。
注意到数组变化的一种方法是首先将数据属性分配为空,然后在安装的方法中分配一个数组。稍后更新反应式数组的另一种方法是使用数组变异方法(如 push)或非变异方法(如 map)生成新数组并用新数组替换旧数组。
Vue.component('profile-grid', {
template: `
<section>
<div>{{profiles && profiles.length ? profiles : ''}} </div>
<div>{{profilesTwo && profilesTwo.length ? profilesTwo : ''}}</div>
</section>`,
data () {
return {
profiles: null,
profilesTwo: []
};
},
created () {
//console.log("I was just created")
},
mounted () {
//console.log("I was just mounted")
this.profiles = ['1', '2', '3'];
this.profilesTwo = ['5', '4', '6'].map(item => item)
}
});
new Vue({
el:'#app',
data () {
return {}
},
mounted () {
console.log('vue instance mounted');
}
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue"></script>
<main id="app">
<profile-grid></profile-grid>
</main>
Run Code Online (Sandbox Code Playgroud)