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

来源:互联网 发布:电影魔方软件 编辑:程序博客网 时间:2024/06/05 01:38

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;                })            }        }    })
原创粉丝点击