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实例了。
  • 相关阅读:
    oracle 更改账户名密码
    mongodb 分片副本集搭建
    爬虫目录
    centos MySQL安装与卸载
    ANACONDA 安装
    chrome 安装
    linux pycharm 安装 idea
    linux 基本命令
    高数18讲 之极限与连续
    高数18讲 之基础知识
  • 原文地址:https://www.cnblogs.com/hjptopshow/p/9239176.html
Copyright © 2011-2022 走看看