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

来源:互联网 发布:大数据解决方案公司 编辑:程序博客网 时间:2024/06/05 21:12
  • 说明: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);// 获取组件的方法        }      }
原创粉丝点击