工作238:Vue.js中this.$nextTick()的使用
this.$nextTick()將回調(diào)延遲到下次 DOM 更新循環(huán)之后執(zhí)行。在修改數(shù)據(jù)之后立即使用它,然后等待 DOM 更新。它跟全局方法 Vue.nextTick 一樣,不同的是回調(diào)的 this 自動(dòng)綁定到調(diào)用它的實(shí)例上。
假設(shè)我們更改了某個(gè)dom元素內(nèi)部的文本,而這時(shí)候我們想直接打印出這個(gè)被改變后的文本是需要dom更新之后才會(huì)實(shí)現(xiàn)的,也就好比我們將打印輸出的代碼放在setTimeout(fn, 0)中;
先來第一個(gè)例子看一看
<template><section><div ref="hello"><h1>Hello World ~</h1></div><el-button type="danger" @click="get">點(diǎn)擊</el-button></section> </template> <script>export default {methods: {get() {}},mounted() {console.log(333);console.log(this.$refs['hello']);this.$nextTick(() => {console.log(444);console.log(this.$refs['hello']);});},created() {console.log(111);console.log(this.$refs['hello']);this.$nextTick(() => {console.log(222);console.log(this.$refs['hello']);});}} </script>可以根據(jù)打印的順序看到,在created()鉤子函數(shù)執(zhí)行的時(shí)候DOM 其實(shí)并未進(jìn)行任何渲染,而此時(shí)進(jìn)行DOM操作并無作用,而在created()里使用this.$nextTick()可以等待dom生成以后再來獲取dom對象
然后來看第二個(gè)例子
<template><section><h1 ref="hello">{{ value }}</h1><el-button type="danger" @click="get">點(diǎn)擊</el-button></section> </template> <script>export default {data() {return {value: 'Hello World ~'};},methods: {get() {this.value = '你好啊';console.log(this.$refs['hello'].innerText);this.$nextTick(() => {console.log(this.$refs['hello'].innerText);});}},mounted() {},created() {}} </script>根據(jù)上面的例子可以看出,在方法里直接打印的話, 由于dom元素還沒有更新, 因此打印出來的還是未改變之前的值,而通過this.$nextTick()獲取到的值為dom更新之后的值
this.$nextTick()在頁面交互,尤其是從后臺獲取數(shù)據(jù)后重新生成dom對象之后的操作有很大的優(yōu)勢
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的工作238:Vue.js中this.$nextTick()的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vb文件服务器例程,利用VB进行服务器编
- 下一篇: 前端学习(2714):重读vue电商网站