如何更改Vue更新钩子? [英] How to get changes in Vue updated hook?
问题描述
如果我有类似的Vue组件:
If I have a Vue component like:
<script>
export default {
updated() {
// do something here...
}
};
</script>
无论如何都要获得导致更新的更改?就像 watch
钩子接受上一个和下一个数据的参数一样?
is there anyway to get the changes that resulted in the update? Like how watch
hooks accept arguments for previous and next data?
watch: {
someProp(next, prev) {
// you can compare states here
}
}
React似乎在 componentDidUpdate
钩子中这样做,所以我假设Vue有类似但我可能错了。
React seems to do this in componentDidUpdate
hooks, so I'm assuming Vue has something similar but I could be wrong.
推荐答案
更新
生命周期挂钩不提供任何有关内容的信息导致Vue组件实例更新。对数据更改做出反应的最佳方法是使用观察者。
The updated
lifecycle hook doesn't provide any information on what caused the Vue component instance to be updated. The best way to react to data changes is by using watchers.
但是,如果您正在尝试调查导致更新以进行调试的原因,则可以存储引用到Vue实例的数据状态并将其与更新时的状态进行比较。
However, if you're trying to investigate what caused an update for debugging purposes, you can store a reference to the state of the Vue instance's data and compare it to the state when updated.
这是一个使用lodash记录更改的属性名称的示例脚本,触发更新:
Here's an example script using lodash to log the name of the property that changed, triggering the update:
updated() {
if (!this._priorState) {
this._priorState = this.$options.data();
}
let self = this;
let changedProp = _.findKey(this._data, (val, key) => {
return !_.isEqual(val, self._priorState[key]);
});
this._priorState = {...this._data};
console.log(changedProp);
},
这是有效的,因为前缀为下划线字符的属性保留供内部使用,不适用于绑定。这可以保存在mixin中,以便在需要以这种方式调试Vue组件时使用。
This works because properties prepended with the underscore character are reserved for internal use and are not available for binding. This could be saved in a mixin to use whenever you needed to debug a Vue component this way.
这篇关于如何更改Vue更新钩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!