前端

适用范围:

  • 在修改数据之后立即使用它,然后等待 DOM 更新。

梗概:

  • 等待下次 DOM 更新循环
    • Vue的dom节点是异步操作的当数据更新后,视图还没有渲染,此时获取页面上的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>
methods:{
  testClick:function(){
    let that=this;
    that.testMsg="修改后的值";
    that.$nextTick(function(){
      console.log(that.$refs.aa.innerText);  //输出:修改后的值
    });
  }
}

1. 之一:

setup() {
  const firstName = ref('')
  const lastName = ref('')
 
  watch([firstName, lastName], (newValues, prevValues) => {
    console.log(newValues, prevValues)
  })
 
  const changeValues = async () => {
  firstName.value = 'John' // 打印 ["John", ""] ["", ""]
  await nextTick()
  lastName.value = 'Smith' // 打印 ["John", "Smith"] ["John", ""]
 
  return { changeValues }
}

2. 之一:

import { createApp, nextTick } from 'vue'
 
const app = createApp({
  setup() {
    const message = ref('Hello!')
    const changeMessage = async newMessage => {
      message.value = newMessage
      await nextTick()
      console.log('Now DOM is updated')
    }
  }
})