# ref属性:
1. 被用来给元素或者子组件注册引用信息 (id的替代者)
2. 应用在html上获取的是真实的DOM元素,应用在组件标签上获取的是组件实例对象(vc)
3. 使用方式:
打标识:<h1 ref="xxx"> .... </h1> 或 <School ref="xxx"></School>
获取:this.$refs.xxx
举例说明:
**App.vue**
<template>
<div>
<h1 v-text="msg" ref="title"></h1>
<button ref="btn" @click="showDom">点我输出上方的DOM元素</button>
<School ref="sch"/>
</div>
</template>
<script>
//引入School组件
import School from './components/School'
export default {
name:'App',
components:{School},
data(){
return {
msg:"欢迎学习!"
}
},
methods:{
showDom(){
console.log(this.$refs.title)
}
}
}
</script>
**School.vue**
<template>
<div>
<h1>学习名称: {{ name }}</h1>
<h1>学校地址: {{ address }}</h1>
</div>
</template>
<script>
export default {
name:'School',
data(){
return{
name:'清华大学',
address:'北京'
}
}
}
</script>
ref属性
于 2022-10-11 14:17:18 首次发布