zoukankan      html  css  js  c++  java
  • 关于vue里的$refs属性

    vuejs的极大程度的帮助减少了对dom的操作,他主要通过添加ref属性,但是当获取this.$refs属性时,稍有不注意就会输出undefined导致我们对dom节点的操作报错。

    this.$refs.xxx为undefined的几种情况记录:

    1、在created里钩子函数中调用

    原因:created()在实例创建完成后被立即调用。在这一步,实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。然而,挂载阶段还没开始,$el 属性目前不可见。所以this.$refs压根就调不到那个dom,因为页面还没有挂载上去。

    解决:在mounted () 钩子函数中调用

    注意:在此种情况中,元素节点一定是直接写在html中的,而不是通过数据或者条件渲染的

    2、数据或条件渲染(v-if,v-show)之后的调用

    原因:

    /** ref
    本身作为渲染结果被创建,在初始渲染的时候不能访问他们,是不存在的
    $refs不是响应式的,只在组件渲染完成后才填充
    用于元素或子组件注册引用信息,注册完成,将会注册在父组件$refs对象上
    调用对象是否和v-if结合使用
    ref不是响应式的,所有的动态加载的模板更新它都无法相应的变化。
    */
    解决:可以通过setTimeOut(()=>{...}, 0)来实现
     
    代码说明:
    <template>
      <div>
        <p ref="testText">this is a test data</p>
        <p v-if="msg" ref="msgText">{{msg}}</p>
        <button @click="handleClick">点一下</button>
      </div>
    </template>
    
    <script>
    import { setTimeout } from 'timers';
    export default {
      data () {
        return {
          text: 'message show',
          msg: ''
        }
      },
      created () {
        console.log(this.$refs.testText)    // undefined
        // this.$refs.testText.style.color = '#f00'
      },
      mounted () {
        console.log(this.$refs.testText)  //  <p data-v-5752faac="" style="color: rgb(255, 0, 0);">this is a test data</p>
        console.log(this.$refs.msgText)     // undefined
        this.$refs.testText.style.color = '#f00'
      },
      methods: {
        handleClick () {
          this.msg = 'msg show'
          console.log(this.$refs.msgText)   // undefined
          setTimeout(() => {
            this.$refs.msgText.style.color = '#eee'
            console.log(this.$refs.msgText) // <p data-v-5752faac="" style="color: rgb(238, 238, 238);">msg show</p>
          }, 0)
        }
      }
    }
  • 相关阅读:
    Codeforces Round #217 (Div. 2)B. Berland Bingo
    走迷宫1 bnu 1054
    MFC 对话框背景图片
    用Visual C++从位图文件生成任意形状的窗口
    poj 2245 Lotto
    poj 1797 Heavy Transportation
    poj 2253 Frogger
    poj 1125 Stockbroker Grapevine
    B. Books
    【转】阻塞与非阻塞socket的优缺点
  • 原文地址:https://www.cnblogs.com/layaling/p/11354333.html
Copyright © 2011-2022 走看看