vue之$nextTick详解

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

场景解释:

<template>
  <div>
    <input >
    <button @click="Btnclick">按钮</button>
  </div>
</template>

<script>
import { mixinsTest } from './mixins';
export default {
  name: '',
  components: {},
  mixins: [mixinsTest],
  props: {},
  data() {
    return {
      names: '我是主线de',
      bState: false
    };
  },
  watch: {},
  computed: {},
  created() {
    console.log('我是主线');
    console.log(this.names);
  },
  mounted() {
    this.Btnclick();
  },
  destroyed() {},
  methods: {
    Btnclick() {
      this.bState = true;
      this.$nextTick(() => {
        document.getElementById('keywords').focus();
      });
    }
  }
};
</script>
<style  scoped>
</style>

比如刚开始这个vue组件里面有一个v-show隐藏 的input框,然后需要在mounted里面去操作这个DOM,这个时候,如果不用$nextTick就会只是显示而不会聚焦,如果用$nextTick就ok

具体参考https://segmentfault.com/a/1190000012861862?utm_source=tag-newest