gpt4 book ai didi

javascript - vm.$set 和 Vue.set 有什么区别?

转载 作者:搜寻专家 更新时间:2023-10-30 22:07:42 27 4
gpt4 key购买 nike

我仔细阅读并重新阅读了 Vue 文档 "Reactivity in Depth"vm.$set 的 API和 Vue.set但我仍然很难确定何时使用哪个。能够区分这两者对我来说很重要,因为在我当前的 Laravel 项目中,我们正在动态设置对象的许多属性。

文档中的区别似乎在于 vm.$set 是“对于 Vue 实例”而 Vue.set 是“对于普通数据对象”和 Vue.set 是全局的:

However, there are ways to add a property and make it reactive afteran 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

最后,我想知道执行上述操作的第 3 个“选项”(一次添加多个属性)是否可以用作上述 2 个选项中的任何一个的等效替代(通过仅添加 1 个属性来代替)的多个)?

Sometimes you may want to assign a number of properties on to anexisting 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 theoriginal 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 模型本身。因此,Vue.set 现在用于那些您有对 react 对象的引用但没有对它所属的 View 模型的引用的情况。

关于javascript - vm.$set 和 Vue.set 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671106/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com