Abr*_*Voy 6 javascript vue.js vuejs2
我的Vue组件包含以下代码:
<script>
export default {
data() {
return {
sailNames: []
}
},
methods: {
showName: function(e) { // [3] called by @click event from DOM
console.log(this.sailNames); // [4] shows: [__ob__: Observer]
},
getJsonData() { // [1] called on created() hook
$.getJSON("./src/res/sails.json", function(data) {
const sailNames = [];
$.each(data, function(i, names) {
sailNames.push(names);
});
this.sailNames = sailNames;
console.log(this.sailNames);
console.log(sailNames); // [2] both logs give the same output
});
}
}
}
(...)
Run Code Online (Sandbox Code Playgroud)
我想知道,为什么[__ob__: Observer]在记录点[4]的状态时得到此信息。如您所见,数组是在本data节中定义的,然后它从局部变量获取值并进行检查:局部变量和全局变量都相同(点[2])。
然后,当用户单击showName分配了方法的元素(pt。[3])时,我希望看到与pt中相同的输出。[2],但[__ob__: Observer]出现在控制台中。
那里发生了什么事?我应该如何调用数组以获取其值?
箭头函数表达式的语法比函数表达式更短,并且没有自己的 this、arguments、super 或 new.target。尝试用箭头函数替换函数表达式。
<script>
export default {
data() {
return {
sailNames: []
}
},
methods: {
showName(e){
console.log(this.sailNames);
},
getJsonData() {
$.getJSON("./src/res/sails.json", (data) => {
const sailNames = [];
$.each(data, function(i, names) {
sailNames.push(names);
});
this.sailNames = sailNames;
});
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8325 次 |
| 最近记录: |