Vue-ref属性

ref属性是什么?

可以辅助开发者获取DOM元素或者组件的引用

什么意思?

我们可以使用jQuery的$来获取DOM元素,或者在原生中使用querySelector等获取到DOM元素并对其做出相应的操作

在Vue中,我们可以使用ref属性来获取DOM元素甚至组件引用来做出相应的操作

所以在Vue项目中,我们不会去使用jQuery,这也是jQuery慢慢淡出人们视线的主要原因之一

目录

ref引用DOM元素

ref定义

 ref引用组件实例

Son.vue:

扫描二维码关注公众号,回复: 14282780 查看本文章

App.vue:


ref引用DOM元素

首先我们需要在想要操作的元素标签中添加ref属性:

<div ref="xxxx"></div>

比如我们通过点击之后触发如下操作:

this.$refs.xxxx.style.color = 'red'

为什么要这样写呢?

我们通过例子来具体解析一下:

<div class="serach" @click="clickbox" ref="xxxx">
<script>
export default {
  methods:{
    clickbox(){
      console.log(this)
    }
  }
}
</script>

我们看到得到的当前组件实例,里面有一个$refs里面有一个DOM元素,而这个DOM元素不是别人,正是我们给到ref属性的那个元素:

this.$refs.xxxx.style.backgroundColor = 'red'

 我们会用了,但是ref哪来的?

ref定义

每一个Vue实例上都会包含一个refs对象,里面则存储着对应的DOM元素或者组件的引用,默认情况下组件的$refs指向的是一个空对象,就像这样:

<div class="serach" @click="clickbox">
<!--模板中现在是没有任何一个元素绑定ref属性--!>
console.log(this)


 ref引用组件实例

相同的,我们给组件标签添加ref属性

<Son ref="sonRef"></Son>

父组件就可以直接调用子组件的方法:

this.$refs.sonRef.子组件方法

假如我们想点击父组件元素让子组件元素背景颜色改变:

Son.vue:

<template>
  <div id="son">
     <button @click="bgcolor" ref="sonColor">点我变红</button>
  </div>
</template>

<script>

export default{
    methods:{
        bgcolor(){
            this.$refs.sonColor.style.backgroundColor = 'red'
        }
    }
}

</script>

App.vue:

<template>
  <div id="app">
    <p>我是App.vue文件</p>
    <Son ref="sonRef"></Son>
    <div class="serach" @click="clickbox" ref="xxxx">点我让子组件元素变红
    </div>
  </div>
</template>

<script>
import Son from '@/components/Son.vue'

export default {
  methods:{
    clickbox(){
      this.$refs.sonRef.bgcolor()
    }
  },
  components:{
    Son
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_63836026/article/details/124537473