Vue.nextTick() 秒速五厘米 2022-11-20 09:35 180阅读 0赞 一、定义: 在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。所以就衍生出了这个获取更新后的DOM的Vue方法。所以放在Vue.nextTick()回调函数中的执行的应该是会对DOM进行操作的 js代码;nextTick(),是将回调函数延迟在下一次dom更新数据后调用,简单的理解是:当数据更新了,在dom中渲染后,自动执行该函数。 二、举例: 1、不使用nextTick()获取更新后的DOM值: <template> <div class="hello"> <div> <button id="firstBtn" @click="testClick()" ref="aa">{ {testMsg}}</button> </div> </div> </template> <script> export default { name: 'HelloWorld', data () { return { testMsg:"原始值", } }, methods:{ testClick:function(){ let that=this; that.testMsg="修改后的值"; console.log(that.$refs.aa.innerText); //that.$refs.aa获取指定DOM,输出:原始值 } } } </script> ![20201028100353625.png][] 即使加了watch: watch: { testMsg: { handler(newName, oldName) {}, immediate: true } }, 打出的仍是原始值: ![20201028100848791.png][] 2、使用nextTick()获取更新后的DOM值: <!-- @format --> <template> <div class="hello"> <div> <button id="firstBtn" @click="testClick()" ref="aa">{ {testMsg}}</button> </div> </div> </template> <script> export default { name: 'HelloWorld', data() { return { testMsg: '原始值' }; }, methods: { testClick: function() { let that = this; that.testMsg = '修改后的值'; that.$nextTick(function() { console.log(that.$refs.aa.innerText); //输出:修改后的值 }); } } }; </script> ![20201028101127391.png][] 三、用法:常用v-if和nextTick配合的方法来强制刷新子组件: <Son v-if="sonRefresh"></Son> data(){ return { sonRefresh: true } } // 下面这段内容写在父组件需要更新子组件的地方 this.sonRefresh= false; this.$nextTick(() => { this.sonRefresh= true; }); 如我: <div v-show="isThirdShow"> <div class="query-div"> <el-button @click="search()" type="primary">搜索</el-button> </div> <MyChild v-if="thirdId" :id="thirdId" ></MyChild> </div> //重新加载 search() { let tem = this.thirdId; this.thirdId = ''; this.$nextTick(() => { this.thirdId = tem; }); } [20201028100353625.png]: /images/20221120/0ffb25b185aa4436ace39011aa96ee8d.png [20201028100848791.png]: /images/20221120/04c8c61d51c640aa83948f4ef76f8d13.png [20201028101127391.png]: /images/20221120/8f3fa35b358247d89f1f271298ae3743.png
还没有评论,来说两句吧...