网络编程
位置:首页>> 网络编程>> JavaScript>> vue基本使用--refs获取组件或元素的实例

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

作者:晨曦之光11  发布时间:2024-05-02 16:35:20 

标签:vue,refs,组件,元素

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

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

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

添加ref属性


<div id="app">
 <h1 ref="h1Ele">这是H1</h1>
 <hello ref="ho"></hello>

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

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


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

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

来源:https://blog.csdn.net/qq_21796899/article/details/78752703

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com