vue基本使用--refs获取组件或元素的实例

2023-06-25,,

说明:vm.$refs 一个对象,持有已注册过 ref 的所有子组件(或HTML元素)

使用:在 HTML元素 中,添加ref属性,然后在JS中通过vm.$refs.属性来获取

注意:如果获取的是一个子组件,那么通过ref就能获取到子组件中的data和methods

添加ref属性

<div id="app">
  <h2 ref="h2Ele">这是H1</h2>
  <hello ref="ho"></hello>

  <button @click="getref">获取H1元素</button>
 </div>

获取注册过 ref 的所有组件或元素

methods: {
    getref() {
     // 表示从 $refs对象 中, 获取 ref 属性值为: h2ele DOM元素或组件
      console.log(this.$refs.h2Ele.innerText);
      this.$refs.h2ele.style.color = 'red';// 修改html样式

     console.log(this.$refs.ho.msg);// 获取组件数据
     console.log(this.$refs.ho.test);// 获取组件的方法
    }
   }

以上这篇vue基本使用--refs获取组件或元素的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。

《vue基本使用--refs获取组件或元素的实例.doc》

下载本文的Word格式文档,以方便收藏与打印。