Vue将属性添加到数据根级别并使其具有反应性 [英] Vue add property to data root level and make it reactive

查看:28
本文介绍了Vue将属性添加到数据根级别并使其具有反应性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

let myData = {
    a: 1
}

const app = new Vue({
    data: myData
});

正如Vue docs所说的,当我们尝试添加如下所示的属性时,新的属性不是被动的:

As Vue docs says when we try to add a property like below, the new property isn't reactive:

myData.b = 12;
console.log(app.b); // undefined

Vue文档建议使用 Vue.set :

Vue docs suggests using Vue.set:

Vue.set(myData, 'b', 12);
console.log(app.b); // still undefined

Vue文档说, Vue.set 为响应对象添加了一个属性!

Vue docs says Vue.set adds a property to a reactive object!

但是我想在数据的根目录级别添加 b .我不知道如何使 b 具有反应性.

But I want to add b to the data's root level. I don't know how to make b reactive.

推荐答案

文档明确指出您无法添加顶部

Vue不允许将新的根级别反应性属性动态添加到已创建的实例中.

Vue does not allow dynamically adding new root-level reactive properties to an already created instance.

必须将密钥添加到根级别对象,以便以后进行更新.

You must add a key to the root level object so you can update it later.

您可以:

  • 使用要更新的默认值创建一个密钥.这意味着您需要事先知道密钥
  • 使用通用键(例如 dynamicProps )创建一个空对象,并使用 Vue.set 在运行时向其添加动态键.
  • create a key with a default value that you'll update. This means that you know the key before hand
  • create an empty object with a generic key (for instance dynamicProps) and use Vue.set to add dynamic keys at runtime to it.

这篇关于Vue将属性添加到数据根级别并使其具有反应性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆