我正在学习 Vue,并且在同一页面上有两个实例,vm1
和 vm2
。
首先,范围界定很奇怪。实例属性的范围由 DOM 元素而不是花括号中的点运算符决定:
{{ attr1 }}
而不是 {{ vm.attr1 }}
不仅如此,当属性不存在时,神奇的作用域也会默默失败!
下面的代码执行没有错误。请注意 toggle
引用 vm
上不存在的 is_visible
:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"</script>
<script>
window.onload = function() {
var vm1 = new Vue({
el: '#vm1',
data: {
message: 'vm1',
},
methods:{
toggle: function(){
this.is_visible = !this.is_visible;
}
}
});
var vm2 = new Vue({
el: '#vm2',
data: {
message: 'vm2',
},
});
};
</script>
</head>
<body>
<div id="vm1">
<h1 v-on:click="toggle()">{{ message }}</h1>
</div>
<div id="vm2">
<h1>{{ message }}</h1>
</div>
</body>
</html>
最佳答案
Instance attributes are scoped by the DOM element rather than dot operator in curly braces
{{ attr1 }} rather than {{ vm.attr1 }}
是的,这就是在模板中访问 Vue 属性的方式(不引用 vm
或 this
)。
the magical scoping silently fails when the attribute doesn't exist!
这不是无声的失败。这恰好是有效的 JavaScript。在 toggle()
中,代码附加了一个名为 is_visible
的新属性,并将其值设置为其自身的否定值。最初,它是未定义的,因此否定结果为 true
。
function Foo() {
console.log({foo1: this.foo});
this.foo = !this.foo;
console.log({foo2: this.foo});
}
new Foo();
Vue 并不要求所有属性都在 data()
中声明。您可以随时将新属性附加到组件实例。但是,未在 data()
中声明的属性是非响应式的。这对于不需要在模板中的局部变量(例如计时器 ID)非常有用。
关于javascript - 访问 Vue 实例上不存在的属性失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52266952/