Vue 中 $refs的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/devincob/article/details/85100481
  • 说明:vm.$refs 一个对象,持有已注册过 ref 的所有子组件(或HTML元素)
  • 使用:在 HTML元素 中,添加ref属性,然后在JS中通过**vm.$refs.**属性来获取
  • 注意:如果获取的是一个子组件,那么通过ref就能获取到子组件中的data和methods

添加ref属性

<div id="app">
    <h1 ref="h1Element">这是H1</h1>
    <hello ref="customize"></hello>
    <button @click="onClick">获取H1元素</button>
</div>

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

methods: {
        getref() {
          // 表示从 $refs对象 中, 获取 ref 属性值为: h1Element DOM元素或组件
          console.log(this.$refs.h1Element.innerText);
          this.$refs.h1Element.style.color = 'red';// 修改html样式
          console.log(this.$refs.customize.msg);// 获取组件数据
          console.log(this.$refs.customize.test);// 获取组件的方法
        }
      }

--------------------------------------------------------------------------分割线--------------------------------------------------------------------------
在这里插入图片描述

在这里插入图片描述
--------------------------------------------------------------------------分割线--------------------------------------------------------------------------
在这里插入图片描述

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

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

<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>

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

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

<template>
  <div class="home">
    <classitem ref="classRef"></classitem>
  </div>
</template>

<script>
  import classitem form "@components/classitem"
export default {
  name: 'index',
  components:{classitem },
  data() {
    return { }
  },
  methods: {},
  mounted() {
    this.$refs.classRef.$el.style.height = window.screen.height+'px'
  }
}
</script>

注:由于是给子组件添加 r e f ref,所以必须添加 el(this. r e f s . c l a s s R e f . refs.classRef. el)。

猜你喜欢

转载自blog.csdn.net/devincob/article/details/85100481