アプリケーションシナリオ:この
this.$nextTick()
メソッドが主に使用され随数据改变而改变的dom应用场景中
ます。vueでのデータとdomレンダリングは非同期であるため、データを使用してdom構造を変更するなどの操作$nextTick()
は、このコールバック関数に配置する必要があります。
created()で使用するメソッドの場合、domはレンダリングされていません。この時点でフック関数でdom割り当てデータ(または他のdom操作)を実行すると、無駄と変わりません。したがってcreated()钩子函数进行的DOM操作一定要放在Vue.nextTick()的回调函数中
、、、および対応するto created()がマウントされます()のフック関数は、domが完全にレンダリングされた後にデータのレンダリングを開始するため、mounted()でdomを操作するときに基本的にレンダリングの問題はありません。
簡単に理解すると、vue.jsのthis。$ nextTick()はデータを待機する役割を果たします。つまり、一部のコールバックを遅延させ、DOMが更新されるまで待機してから実行を開始します。簡単に言えば、setTimeout()の役割と同等です。
次に例を示し
ます。1。dom要素データを変更してからdomを出力する場合は、domの更新が完了するまで待つことができます
。2 。イベントを通じてデータデータを変更してから、domを出力し、印刷します。メソッド内で直接dom要素が更新されていないため、前の値は変更されず、this。$ nextTick()によって取得された値はdom更新後の値です。
<template>
<section>
<div ref="hello">
<h1 ref="hello">{
{ value }}</h1>
</div>
<button type="warn" @click="get">点击</button>
</section>
</template>
<script>
export default {
data() {
return {
value:'beautiful girl'
};
},
mounted() {
console.log("mounted首次执行")
console.log("mounted11",this.$refs["hello"])
this.$nextTick(function(){
console.log("mounted 中执行netxtTick函数")
console.log("mounted22",this.$refs["hello"])
})
},
created() {
console.log("created首次执行")
console.log("created11",this.$refs["hello"])
this.$nextTick(function(){
console.log("created 中执行netxtTick函数")
console.log("created22",this.$refs["hello"])
})
},
methods: {
get(){
this.value="漂亮女孩!"
console.log("methods11",this.$refs["hello"].innerText)
this.$nextTick(function(){
console.log("methods22",this.$refs["hello"].innerText)
})
}
}
};
</script>
<style scoped>
</style>