我有一个基于某些嵌套状态的组件。例如
<rect width="some.deep.state.width">
每当此路径中的任何对象发生更改(不是新设置)时,即使没有任何更改,组件也会重新呈现。
例如,以下会导致重新渲染:
Vue.set(some.deep, 'newProp', something)
可以想象,这是非常不受欢迎的,尤其是在商店中使用嵌套状态并且某些数组值发生变化时。
在我的例子中,我在我的商店中保存了多个实体,每当添加该实体的新实例时,即使没有任何更改,基于该实体的所有组件都会重新呈现。
那么有没有办法阻止收集这个(技术)部门(双关语)? 我可以通过某种机制阻止 Vue 收集 dep 吗?
PS:我知道,这个机制在其他地方很有用。就我而言,这是不需要的
显示该行为的 Codesandbox(在控制台中):https://codesandbox.io/s/vuejs-playground-forked-sx534?file=/components/hello.js
内联示例 - 触发更新:
const app = new Vue({
el: '#app',
data: function () {
return { some: { nested: { prop: 6 }}}
},
created: function () {
console.log('component created')
setTimeout(function () {
Vue.set(this.some, 'otherProp', 10)
}.bind(this), 2000)
},
updated: function () {
console.log('component updated')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Prop: {{ some.nested.prop }}
</div>
最佳答案
我认为这个问题并不能阻止组件收集不必要的依赖项。 Vue renderWatcher 收集some.deep
使用 <rect width="some.deep.state.width">
时已经存在依赖关系在模板中。然后执行 Vue.set(this.some.deep, 'newProp', something)
会通知所有收集some.deep
watcher 其中包括将触发重新渲染的 renderWatcher。
我有一个 hack 解决方案,如果您确保不想重新渲染,则停止 renderWatcher 运行。
const app = new Vue({
el: '#app',
data: function () {
return { some: { deep: { prop: 6 }}}
},
created: function () {
console.log('component created')
setTimeout(function () {
console.log('trigger rerender?')
Vue.set(this.some, 'otherProp', 10)
this.preventRerender()
}.bind(this), 2000)
},
render(h) {
console.log('render')
return h('div', this.some.deep.prop)
},
methods: {
// keep calling at the code end
preventRerender() {
this._watcher.active = false
this.$nextTick(() => {
this._watcher.active = true
})
}
}
})
你必须注意到更新的钩子(Hook)仍然被触发。
关于javascript - 如何防止组件收集不必要的依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63355747/