Vue技术_ref属性(被用来给元素或子组件注册引用信息)

文章详细介绍了Vue框架中ref属性的用途,包括作为HTML元素和组件的引用,以及如何通过this.$refs获取它们。通过案例展示了如何使用ref属性来操作DOM元素和子组件实例,强调了ref相对于id的优势在于可以直接访问组件的方法和数据,简化了DOM操作,提高了开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、ref属性解释

1.被用来给元素或子组件注册引用信息(id的替代者)

2.应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)

3.使用方式:打标识: <h1 ref="xxx">.....</h1>或<School ref="xxx"></School>

 获取方法:this.$refs.xxx

二、 ref 属性的使用方式 & 获取方式

2.1 标记 html 标签元素:

<h1 ref="xxx">.....</h1>

2.2 标记子组件:

<School ref="xxx"></School>

2.3 获取标识的元素或子组件:

this.$refs.xxx

三、使用ref属性案例

3.1 使用 ref 属性标记 html 标签元素:

ref 属性应用在 html 标签元素上,获取的是对应的真实 DOM 元素

<template>
  <div>
    <h1 ref="hello">Hello World</h1>
    <button @click="showH1">showH1</button>
  </div>
</template>

<script>
export default {
  name: 'App'
  methods: {
    showH1() {
      console.log(this.$refs.hello)
      console.log(this.$refs)
    }
  }
}
</script>

<style>

</style>

在这里插入图片描述

3.2 使用 ref 属性标记子组件:

ref 属性应用在组件标签上,获取的是对应组件实例对象

MySchool组件:

<template>
  <div class="demo">
    <h2>学校:{{name}}</h2>
    <h2>地址:{{address}}</h2>
  </div>
</template>

<script>
export default {
  name: 'MySchool',
  data() {
    return {
      name: 'SGG',
      address: 'Beijing'
    }
  },
}
</script>

<style>
  .demo {
    background-color: chocolate;
  }
</style>

App组件:

<template>
  <div>
    <h1 ref="hello">Hello World</h1>
    <MySchool ref="myschool"></MySchool>
    <button @click="showH1">showH1</button> <br><br>
    <button @click="showMySchool">showMySchool</button>
  </div>
</template>

<script>
// 导入子组件
import MySchool from './components/MySchool.vue'

export default {
  name: 'App',
  components: {
    MySchool,
  },
  methods: {
    showH1() {
      console.log(this.$refs.hello)
      console.log(this.$refs)
    },
    showMySchool() {
      console.log(this.$refs.myschool)
      console.log(this.$refs)
    }
  }
}
</script>

<style>

</style>

在这里插入图片描述

3.3 使用 id 获取元素或子组件 :

<template>
  <div>
    <h1 ref="hello" id="hh">Hello World</h1>
    <MySchool ref="myschool" id="school"></MySchool>
    <button @click="showH1_School">showH1_School</button>
  </div>
</template>

<script>
// 导入子组件
import MySchool from './components/MySchool.vue'

export default {
  name: 'App',
  components: {
    MySchool
  },
  methods: {
    showH1_School() {
      console.log(document.getElementById('hh'))
      console.log(document.getElementById('school'))
    }
  }
}
</script>

<style>
</style>

在这里插入图片描述

四、总结 

1. 使用ref属性获取子组件时,可以直接获取到子组件的实例对象,而不仅仅是子组件编译解析后的模板。这意味着你可以直接调用子组件的方法、访问子组件的数据等,方便后期对子组件进行操作和通信。

2. 而使用id则需要手动操作DOM,并且只能通过DOM的选择器方法来获取对应的DOM元素,无法直接获取组件实例对象。

3. 综上所述,使用ref属性可以简化DOM操作,并且获取子组件时可以直接获取到组件实例对象,提供了更方便灵活的操作和通信方式。这使得Vue中的开发更加便利和高效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值