zoukankan      html  css  js  c++  java
  • Vue 获取dom元素之 ref 和 $refs 详解

    一、$refs

      一个对象,持有ref注册过的所有元素或子组件。(注册过的 ref 的集合)

    二、ref

      被用来给元素或子组件注册引用信息。若用在dom元素上,引用指向的就是dom元素;若用在子组件上,引用指向的是子组件。(引用信息注册在父组件的$refs对象上)

    <!-- `vm.$refs.p` will be the DOM node -->
    <p ref="p">hello</p>
    
    <!-- `vm.$refs.child` will be the child component instance -->
    <child-component ref="child"></child-component>

    三、实例

      比如我现在要实现的效果是点击用v-for生成的li ,获取到该元素的值。
      首先要获取当前点击的li元素,我们要做的是:
     
      1、给dom添加点击事件和ref属性。
    <li class="sidebar-list"  v-for="(item, index) in meunList"  @click="setPageMenu(index)" ref="menuItem">
        <router-link class="sidebar-a" :to="{ path: item.listLink }" >{{item.listTitle}}</router-link>
    </li>

      给组件添加ref属性。

    <user-profile ref="profile"></user-profile> 

      2、在点击事件方法中使用ref。

    setPageMenu(index) {
    //这个是获取当前menuItem值,用index来区分当前元素是v-for 产生的数组中的第几个数
        let getMenuText = this.$refs.menuItem[index].innerText;
    }
      访问子组件。
    var child = this.$refs.profile  

      实例参考地址:https://www.cnblogs.com/xianhuiwang/p/6702712.html

  • 相关阅读:
    微信小程序 数组索引 data-“”解释
    Aho-Corasick算法原理(图省事我直接粘贴PPT了)
    神奇的人生
    nginx-学习笔记9
    nginx-学习笔记8
    nginx-学习笔记7
    nginx-学习笔记6
    nginx-学习笔记5
    nginx-学习笔记4
    nginx-学习笔记2
  • 原文地址:https://www.cnblogs.com/candy-Yao/p/9210265.html
Copyright © 2011-2022 走看看