Vue:nextTick作用 - 附带案例讲解

x33g5p2x  于2022-03-06 转载在 其他  
字(2.3k)|赞(0)|评价(0)|浏览(175)

1. Vue.$nextTick - 获取最新渲染的DOM数据

参考:https://segmentfault.com/a/1190000012861862

通俗解释:Vue 在修改数据后,视图不会立刻更新,而是等同一事件循环中的所有数据变化完成之后,再统一进行视图更新 - 即你修改下图变量message是同步任务,但你把数据渲染到页面是异步任务(Vue的视图渲染内部用虚拟DOM组成),只要虚拟DOM更新了数据,那么你就可以获取到最新的渲染数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="G:\VsCode\开源\vue.global.js"></script>
</head>
<body>
    <div id="main-box">
        <div style="margin-top:50px;border: 5px solid red;padding:30px">
            <p ref="sourceContent">{{msg}}</p>
            <p>不使用nextTick获取的sourceContent节点的内容:{{msg2}}</p>
            <p>使用nextTick获取的sourceContent节点的内容:{{msg3}}</p>
            <button @click="test">测试$nextTick</button>
        </div>
       
        <div style="margin-top:50px;border: 5px solid red;padding:30px">
            <div>
                <button @click="switchShow">隐藏/显示Input框, 显示时此Input获得焦点(不使用nextTick)</button>
                <br>
                <span>不使用nextTick</span><input ref="input" v-if="show"></input>
            </div>
   
            <div style="margin-top:50px">
                <button @click="switchShow2">隐藏/显示Input框, 显示时此Input获得焦点(使用nextTick)</button>
                <br>
                <span>使用nextTick</span><input ref="input2" v-if="show2"></input>
            </div>
        </div>        
    </div>
</body>
<script>
    var mainPage = {
        data: function () {
            return {
                msg: "原始信息",
                msg2: "",
                msg3: "",
                num: 1,
                show: false,
                show2: false
            }
        },
        methods: {
            test: function () {
                this.msg = "新消息" + this.num++
                //还没等sourceContent节点渲染完就去拿到节点HTML内容
                this.msg2 = this.$refs['sourceContent'].innerHTML
                //等到sourceContent节点渲染完才去拿节点HTML内容
                this.$nextTick(() => {
                    this.msg3 = this.$refs['sourceContent'].innerHTML
                })
            },
            //此input不会获得焦点,因为input还没渲染出来已经去执行focus方法
            switchShow: function () {
                this.show = !this.show;
                if (this.show) {
                    this.$refs['input'].focus();
                }
            },
            //此input会获得焦点,因为input渲染出来才去执行focus方法
            switchShow2: function () {
                this.show2 = !this.show2;
                if (this.show2) {
                    this.$nextTick(() => {
                        this.$refs['input2'].focus();
                    })
                }
            },
        }
    }
    Vue.createApp(mainPage)
        .mount("#main-box")
</script>
</html>

相关文章

微信公众号

最新文章

更多