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)
        }
      }
    }
  • 相关阅读:
    第123天:移动web开发中的常见问题
    第122天:移动端开发常见事件和流式布局
    第121天:移动端开发基本知识
    第120天:移动端-Bootstrap基本使用方法
    第119天:移动端:CSS像素、屏幕像素和视口的关系
    加入收藏 设为首页代码收藏本页的代码和收藏本站的代码设为首页代码
    JQuery和UpdatePannel的问题
    JS中apply与call的用法
    Sumlime text3 安装包、汉化包、注册码
    使用WITH AS提高性能简化嵌套SQL
  • 原文地址:https://www.cnblogs.com/layaling/p/11354333.html
Copyright © 2011-2022 走看看