这篇文章有点划水,因为只是讲了一个vue里很简单的一个知识点,但是还是要写,因为vue的知识点还是要写完的,趁着这几天不上班,将之前欠下来的知识点全部补充上来,后面可能就不再更新关于vue2.0的东西了,今天这篇文章写的是关于vue中nextTick的使用以及他的使用场景和他的作用
nextTick是vue提供出来更新视图之后回调的函数,也就是说我们在操作dom更新视图的时候,由于vue的视图渲染是异步的,可能会导致一些视图已经更新了,但是我们获取到的视图数据信息不是最新的,使用nextTick可以保证视图在下一次更新之后进行调用
<!--
* @use:
* @description: 测试nextTick用法
* @SpecialInstructions: 无
* @Author: clearlove
* @Date: 2022-01-04 13:35:13
* @LastEditTime: 2022-05-20 15:59:49
* @FilePath: /universal-background-template/src/pages/index.vue
-->
<template>
<div>
<div>
<ul>
<li ref="liNode" v-for="(item, index) in liList" :key="index">
{{ item }}
</li>
</ul>
</div>
<button @click="addOneData">增加一条数据</button>
<b>当前li条数为===〉{{ currLiLenth }}</b>
</div>
</template>
<script>
export default {
name: "index",
data() {
return {
liList: ["java", "js", "c"],
currLiLenth: 0,
};
},
created() {
this.currLiLenth = this.liList.length;
},
methods: {
//增加一条li数据
addOneData() {
this.liList.push(Math.random(10) * 100);
let currLiLen = this.$refs.liNode.length;
console.log(currLiLen);
this.currLiLenth = currLiLen;
},
},
};
</script>
<style lang="less" scoped>
</style>
//增加一条li数据
addOneData() {
this.liList.push(Math.random(10) * 100);
//使用nextTick进行更新dom,会在dom更新之后的下一次进行回调
this.$nextTick(() => {
let currLiLen = this.$refs.liNode.length;
console.log(currLiLen);
this.currLiLenth = currLiLen;
});
},
文章的篇幅比较短,我的目的很简单,用最简单的代码演示出来他的作用所在,毕竟nextTick本身就是这样一个作用,所以也没有必要长篇大论的总结他,上述代码运行有任何问题或者是运行的效果不如预期均可以下方留言!拜拜