美文网首页
3、nextTick

3、nextTick

作者: 苏码码 | 来源:发表于2021-07-01 16:18 被阅读0次

Vue中this.nextTick()的使用 this.nextTick()是将回调延迟到下次DOM更新循环回调后执行。在修改数据之后立即使用它,待Dom更新后执行。它跟全局方法 Vue.nextTick 一样,不同的是回调的 this 自动绑定到调用它的实例上。

<template>
  <div id="app">
    <div ref="name">{{name}}</div>
    <button @click="clickAction1">change</button>
  </div>
</template>

created() {
    console.log("0000")
    console.log(this.$refs["name"]) //  =>  undefined
  },
  mounted() {
    this.name = "apple"
    console.log(1111111)
    console.log(this.$refs["name"].innerText)

    this.$nextTick(() => {
      console.log(333333)
      console.log(this.$refs["name"].innerText)
    })
  },
  beforeUpdate() {
    console.log(222222)
    console.log(this.$refs["name"].innerText)
  },
  updated() {
    console.log(4444444)
    console.log(this.$refs["name"].innerText)
  },
  methods: {
    clickAction1() {
      this.name = "小米"
      console.log(this.$refs["name"].innerText)
       this.$nextTick(() => {
      console.log(555555)
      console.log(this.$refs["name"].innerText)
    })
    }
}
截屏2021-07-01 下午4.04.53.png

可以根据打印的顺序看到,在created()钩子函数执行的时候DOM 其实并未进行任何渲染,而此时进行DOM操作并无作用,而在created()里使用this.$nextTick()可以等待dom生成以后再来获取dom对象
点击change事件

截屏2021-07-01 下午4.15.07.png

修改name后立即获取Dom,元素没有更新,修改name会触发beforeUpdate,此时获取DOm,依然没有更新,随后出发updated,获取Dom 返现已经修改,再执行this,$nextick(),Dom已经被修改了

相关文章

网友评论

      本文标题:3、nextTick

      本文链接:https://www.haomeiwen.com/subject/xkpjultx.html