VUE 关于理解$nextTick()的问题

Vue.js 通常鼓励开发人员沿着“数据驱动”的方式思考,避免直接接触 DOM。this.$nextTick()官方介绍:将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。它跟全局方法 Vue.nextTick 一样,不同的是回调的 this 自动绑定到调用它的实例上。

DOM

<div id="app">
    <p ref="myWidth" v-if="showMe">{{ message }}</p>
    <button @click="getMyWidth">获取p元素宽度</button>
</div>

script

    new Vue({
        el: "#app",
        data: {
            message: 'Hello Vue.js',
            showMe: false
        },
        methods: {
            getMyWidth() {
                this.showMe = true;
                //this.message = this.$refs.myWidth.offsetWidth;
           //报错 TypeError: this.$refs.myWidth is undefined
                this.$nextTick(()=>{
                    //dom元素更新后执行,此时能拿到p元素的属性
                    this.message = this.$refs.myWidth.offsetWidth;
                })
            }
        }
    })

注意:

this.nextTick(callback),当数据发生变化,更新后执行回调。
this.$nextTick(callback),当dom发生变化,更新后执行的回调。

this.$nextTick()放哪里?

因为数据是根据请求之后获取的,所以应该放到请求的回调函数里面。

转自博客:https://blog.csdn.net/weixin_38578293/article/details/78734782

猜你喜欢

转载自blog.csdn.net/a3060858469/article/details/80550284