javascript - Vue实例中的数据错误是否可以丢弃?

标签 javascript vue.js

我的 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/

相关文章:

javascript - Axios POST 返回 "Network Error"即使状态为 200 并且有响应

javascript - Stripe 未被调用

javascript - Vue 从插件发出事件

javascript - 拖放 API 存在问题吗?

javascript - 为什么子元素不隐藏父元素jquery。?

vue.js - react 性丢失 : How to use a "deep" computed setter

vue.js - 在 Vuex 中使用 Framework7 $f7.router.navigate

javascript - 使用 .on() 和 namespace 语法附加多个事件处理程序

javascript - 参数左侧无效 - 引用错误

javascript - 没有 ssl 的 Web 加密 API