11. ref属性
App.vue
<template>
<div>
<h1 ref="title">{{msg}}</h1>
<button ref="btn" @click="showDOM">点我获取上方的DOM元素</button>
<School ref="sch"></School>
</div>
</template>
<script>
import School from "@/components/School";
export default {
name: "App",
components:{School},
data(){
return{
msg:"欢迎学习Vue!"
}
},
methods:{
showDOM(){
//获取ref为title的DOM元素
console.log(this.$refs.title);
console.log(this.$refs.btn);
console.log(this.$refs.sch);
//获取School组件内ref为schoolName的DOM元素
console.log(this.$refs.sch.$refs.schoolName);
}
}
}
</script>
<style scoped>
</style>
School.vue
<template>
<div>
<h2 ref="schoolName">学校名称: {{name}}</h2>
<h2>学校地址: {{address}}</h2>
</div>
</template>
<script>
export default {
name: "School",
data(){
return{
name:"南方IT",
address:"广东"
}
}
}
</script>
<style scoped>
</style>
总结
- 被用来给元素或子组件注册引用信息(id的替代者)
- 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
使用方式:
- 打标识:
....
或 - 获取: this.$refs.xxx
- 打标识: