-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
[vue] 分别说说vue能监听到数组或对象变化的场景,还有哪些场景是监听不到的?无法监听时有什么解决方案? #269
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
能监听是因为已经对该数据设置了observe, 反正则监听不到 |
无法监听时的方案: |
监听不到到使用$set()给对象添加或者修改,向响应式对象中添加一个 property,并确保这个新 property 同样是响应式的,且触发视图更新。详细参数去官网查看使用。 |
由于监听的数据在vue实例新建时就已经确定,且由于是通过Object.defineProperty的get和set实现,因此数组和对象都无法直接监听到添加、删除操作。 数组:
对象:
|
对象:
data: { a: 1}; data.b = 2。b不具备响应式。可通过this.$set(data, 'b', 2)来赋予data.b响应式 数组:
原因: Vue有哪些api处理响应式 |
可以监听的场景数组变化的场景:当你使用数组的变异方法(如 push、pop、splice、shift 等)来修改数组时,Vue能够检测到数组的变化并更新视图。 示例:
对象属性变化的场景:当你直接修改对象的属性或使用 Vue.set 或 this.$set 方法来添加新的响应式属性时,Vue能够检测到对象的属性变化并更新视图。 示例:
无法监听的场景直接修改数组索引或对象属性:如果通过直接修改数组索引或对象属性的方式来进行变化,Vue无法自动检测到变化。 示例:
解决方案: 对于数组,应该使用变异方法(如 splice)来修改数组,或者使用 this.$set 来更新指定索引的值。 通过下标直接修改数组长度:如果通过修改数组的 length 属性来改变数组的长度,Vue无法自动检测到变化。 示例:
解决方案: 应该使用变异方法(如 splice)来修改数组,或者重新赋值一个新的数组来替换原来的数组。 总结来说,Vue能监听到数组或对象变化的主要场景是通过变异方法或特定的操作进行的修改。对于无法监听到的情况,可以使用特定的方法(如 this.$set、Vue.set)或采取其他策略来实现响应式更新。 |
[vue] 分别说说vue能监听到数组或对象变化的场景,还有哪些场景是监听不到的?无法监听时有什么解决方案?
The text was updated successfully, but these errors were encountered: