一、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中的开发更加便利和高效。