Vue 中 $refs 的使用

  • 说明:vm.$refs 一个对象,持有已注册过 ref 的所有子组件(或HTML元素)
  • 使用:在 HTML元素 中,添加ref属性,然后在JS中通过vm.$refs.属性来获取
  • 注意:如果获取的是一个子组件,那么通过ref就能获取到子组件中的data和methods

1.

添加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);// 获取组件的方法
        }
      }

--------------------------------------------------------------------------华丽分割线---------------------------------------------------------------------

è¿éåå¾çæè¿°

è¿éåå¾çæè¿°

--------------------------------------------------------------------------华丽分割线---------------------------------------------------------------------

<div id="app">
  <input type="text" ref="input1"/>
  <button @click="add">添加</button>
</div>

<script>
new Vue({
  el: "#app",
  methods:{
  add:function(){
    this.$refs.input1.value ="22"; //this.$refs.input1 减少获取dom节点的消耗
    }
  }
})
</script>

一般来讲,获取DOM元素,需document.querySelector(".input1")获取这个dom节点,然后在获取input1的值。

但是用ref绑定之后,我们就不需要在获取dom节点了,直接在上面的input上绑定input1,然后$refs里面调用就行。

然后在javascript里面这样调用:this.$refs.input1  这样就可以减少获取dom节点的消耗了

2.

在父组件中通过$ref给子组件动态添加属性,具体代码如下;

注:由于是给子组件添加$ref,所以必须添加$el(this.$refs.classifyfix.$el)

这里写图片描述

以上转发自:https://blog.csdn.net/qq_21796899/article/details/78752703

                     https://blog.csdn.net/lzx18337151076/article/details/78949712

                     https://www.jb51.net/article/138831.htm

                     https://blog.csdn.net/qq_30669833/article/details/78776858

猜你喜欢

转载自blog.csdn.net/u012302552/article/details/81904948