VueVue全家桶

107、vue中$nextTick和$forceUpdate的用

2019-11-15  本文已影响0人  world_7735

1、$nextTick

vm.$nextTick( [callback] )

<html>
    <head>
            <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    </head>
    <body>
        <div id="app">
            <section>
                <div ref="hello">
                  <h1>Hello World ~</h1>
                </div>
                <button type="danger" @click="get">点击</button>
              </section>
          </div>
    </body>
</html>
<script>
new Vue({
  el: '#app',
  methods: {
      get() {
        console.log(0);
      }
    },
    mounted() {
      console.log(333);
      console.log(this.$refs['hello']);
      this.$nextTick(() => {
        console.log(444);
        console.log(this.$refs['hello']);
      });
    },
    created() {
      console.log(111);
      console.log(this.$refs['hello']);
      this.$nextTick(() => {
        console.log(222);
        console.log(this.$refs['hello']);
      });
    }
})
</script>

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

<html>
    <head>
            <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    </head>
    <body>
        <div id="app">
            <section>
                <h1 ref="hello">{{ value }}</h1>
                <button type="danger" @click="get">点击</button>
              </section>
          </div>
    </body>
</html>
<script>
new Vue({
  el: '#app',
  data() {
      return {
        value: 'Hello World ~'
      };
    },
    methods: {
      get() {
        this.value = '你好啊';
        console.log(this.$refs['hello'].innerText);
        this.$nextTick(() => {
          console.log(this.$refs['hello'].innerText);
        });
      }
    },
    mounted() {
    },
    created() {
    }
})
</script>

this.$nextTick()在页面交互,尤其是从后台获取数据后重新生成dom对象之后的操作有很大的优势。

2、this.$forceUpdate()

html:
 
<span class="test">{{egData.value}}</span>
<el-button @click="changeData">改变</el-button>
 -------------------------------
js:
data(){
  return {
 egData: {}
}
 }
-------------------------------
 
 methods:{
changeData () {
    this.egData.value = 'oldValue'
    this.$forceUpdate()  // dom会更新
}
}

但是这种做法并不推荐,官方说如果你现在的场景需要用forceUpdate方法 ,那么99%是你的操作有问题,如上data里不显示声明对象的属性,之后添加属性时正确的做法时用 vm.$set() 方法,所以forceUpdate请慎用。

上一篇 下一篇

猜你喜欢

热点阅读