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)
        }
      }
    }
  • 相关阅读:
    BZOJ 2002: [Hnoi2010]Bounce 弹飞绵羊(分块)
    BZOJ 2648 SJY摆棋子(KD Tree)
    Codeforces Round #441 D. Sorting the Coins(模拟)
    HDU 3400 Line belt (三分套三分)
    HDU 5919 Sequence II(主席树+区间不同数个数+区间第k小)
    HDU 5985 Lucky Coins(概率)
    HDU 5988 Coding Contest(浮点数费用流)
    HDU 5792 World is Exploding(树状数组+离散化)
    HDU 5791 Two(LCS求公共子序列个数)
    HDU 5787 K-wolf Number(数位dp)
  • 原文地址:https://www.cnblogs.com/layaling/p/11354333.html
Copyright © 2011-2022 走看看