我仔细阅读并重新阅读了Vue docs “Reactivity in Depth”以及vm.$set和Vue.set的API,但我仍然很难确定何时使用哪个.我能够区分这两者是很重要的,因为在我目前的Laravel项目中,我们动态地在对象上设置了很多属性.
文档中的区别似乎是vm.$set为“For Vue instance”的语言,而Vue.set为“For plain data objects”且Vue.set为global:
However, there are ways to add a property and make it reactive after
an instance has been created.For Vue instances, you can use the $set(path, value) instance method:
vm.$set('b', 2)
// `vm.b` and `data.b` are Now reactive
For plain data objects, you can use the global Vue.set(object, key,
value) method:
Vue.set(data, 'c', 3)
// `vm.c` and `data.c` are Now reactive
最后,我想知道上面做的第三个“选项”(用于一次添加多个属性)是否可以用作上述2个选项中的任何一个的等效替代(通过仅添加1个属性而不是多个) ?
Sometimes you may want to assign a number of properties on to an
existing object, for example using object.assign() or _.extend().
However, new properties added to the object will not trigger changes.
In such cases, create a fresh object with properties from both the
original object and the mixin object:
// instead of `Object.assign(this.someObject, { a: 1, b: 2 })`
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
解决方法:
这是随着Vue.set的引入而发布的发行说明:
Vue no longer extends Object.prototype with $set and $delete methods.
This has been causing issues with libraries that rely on these
properties in certain condition checks (e.g. minimongo in Meteor).
Instead of object.$set(key, value) and object.$delete(key), use the
new global methods Vue.set(object, key, value) and Vue.delete(object,
key).
所以,.$set曾经在所有对象上都可用 – 它现在只能在View Model本身上使用.因此,当你有一个对被动对象的引用但没有对它所属的视图模型的引用时,Vue.set现在用于这些情况.
原文地址:https://codeday.me/bug/20191004/1852631.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。