zoukankan      html  css  js  c++  java
  • 从Vue.js看nextTick机制

    操作DOM
    在使用vue.js的时候,有时候因为一些特定的业务场景,不得不去操作DOM,比如这样:
    
    <template>
      <div>
        <div ref="test">{{test}}</div>
        <button @click="handleClick">tet</button>
      </div>
    </template>
    export default {
        data () {
            return {
                test: 'begin'
            };
        },
        methods () {
            handleClick () {
                this.test = 'end';
                console.log(this.$refs.test.innerText);//打印“begin”
            }
        }
    }
    打印的结果是begin,为什么我们明明已经将test设置成了“end”,获取真实DOM节点的innerText却没有得到我们预期中的“end”,而是得到之前的值“begin”呢?
    
    访问真实DOM节点更新后的数据
    所以我们需要在修改data中的数据后访问真实的DOM节点更新后的数据,只需要这样,我们把文章第一个例子进行修改。
    
    <template>
      <div>
        <div ref="test">{{test}}</div>
        <button @click="handleClick">tet</button>
      </div>
    </template>
    export default {
        data () {
            return {
                test: 'begin'
            };
        },
        methods () {
            handleClick () {
                this.test = 'end';
                this.$nextTick(() => {
                    console.log(this.$refs.test.innerText);//打印"end"
                });
                console.log(this.$refs.test.innerText);//打印“begin”
            }
        }
    }
    使用Vue.js的global API的$nextTick方法,即可在回调中获取已经更新好的DOM实例了。
  • 相关阅读:
    MySQL与PostgreSQL对比
    Elastic Job3.0
    Nacos Config动态刷新值
    clickhouse数据类型
    字符串和整数之间的转换
    STL之优先队列 priority_queue
    c++智能指针
    springcloud gateway: discovery: locator: enabled: true 解释
    工具资源下载链接 webstorm
    技术链接汇总
  • 原文地址:https://www.cnblogs.com/hjptopshow/p/9239176.html
Copyright © 2011-2022 走看看