updated
执行的频率太高了,希望页面更新之后执行的逻辑,其实nextTick
更合适
数据改变
并且dom
更新之后执行的回调函数new Vue({
// ...
methods: {
// ...
example: function () {
// 修改数据
this.message = ‘changed‘
// DOM 还没有更新
this.$nextTick(function () {
// DOM 现在更新了
// `this` 绑定到当前实例
this.doSomethingElse()
})
}
}
})
demo
<template>
<div>
<h2>update的缺点和解决方案nextTick</h2>
<input type = "text" v-model = "msg"/>
<br/>
<input type = "text" v-model = "info"/>
<h2 ref = "info">info:{{ info }}</h2>
<button @click = "changeInfo">修改info</button>
</div>
</template>
<script>
export default {
updated() {
// 任何数据更新都会触发updated
// 执行频率很高
// 开发中 用的不是很多
// console.log(‘执行啦!‘)
},
data() {
return {
msg: ‘感觉自己萌萌哒!‘,
info: ‘阿珍爱上了阿强‘,
};
},
methods: {
changeInfo() {
// 修改数据
this.info = ‘在一个没有星星的夜晚!‘;
// 页面还没更新
console.log(‘innerHTML:‘, this.$refs.info.innerHTML);
// 数据改变, dom更新完毕
this.$nextTick(() => {
// 绑定this,更新之后的DOM
console.log(‘nextTick-innerHTML:‘, this.$refs.info.innerHTML);
});
},
},
};
</script>
<style></style>
原文:https://www.cnblogs.com/Code-Is-Fun/p/14846391.html