我的 Vue
实例中将有很多变量通过 API 调用进行修改。它们的初始值并不重要。
我希望有一种方法不在虚拟机实例化时定义它们,但这不起作用:
vm = new Vue({
el: "#app",
data: {}
});
vm.number = 3
<div id="app">
{{ number }}
</div>
如果我用 data: { number: null }
替换 data: {}
,代码运行正常。
我想避免的是一连串这样的声明 - 有没有办法在实例化时不声明data
变量?
最佳答案
不完全是。
docs解释 Vue 中的 react 性如何工作,如下所示:
When you pass a plain JavaScript object to a Vue instance as its data option, Vue will walk through all of its properties and convert them to getter/setters using Object.defineProperty.
...
The getter/setters are invisible to the user, but under the hood they enable Vue to perform dependency-tracking and change-notification when properties are accessed or modified.
...
Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion.
所以基本上简单来说,为了使数据值具有反应性并在 API 调用返回时更新,该属性必须从实例化时就存在,因为 Vue 无法检测添加或删除强>.
话虽这么说,您可以按照 @gskema 的建议通过使用占位符对象并将属性附加到该对象来伪造它。这些更改确实会被 Vue 接收到。
所以你可以这样做:
data: {
api: null
}
然后将您的 api 值附加到 api
返回时属性,最后通过 api.number
引用所有数据等等
关于javascript - Vue实例中的数据错误是否可以丢弃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40536545/