通俗的讲,ref特性就是为元素或子组件赋予一个ID引用,通过this.$refs.refName来访问元素或子组件的实例
父组件
<template>
<div>
<button @click="handle()">我爱学习,学习爱我</button>
<UserName ref="child"></UserName>
<p ref="pp">今天天气晴朗</p>
</div>
</template>
<script>
import UserName from "../components/UserName.vue"
export default {
components: {
UserName
},
data() {
return {
}
},
mounted() {
console.log(this.$refs.pp)
},
methods: {
handle() {
this.$refs.child.init()
}
}
}
</script>
子组件
<template>
<div>
<h2>hahahah </h2>>
</div>
</template>
<script>
export default {
methods: {
init() {
console.log('我是小仙女')
}
}
}
</script>
总结:
ref属性定义在父组件中 (写在子组件标签身上),就相当于给子组件取了一个名字,例如ref='child'。
this.$refs.child就是Child组件的 Vue 实例,可以读取Child子组件的各种数据和执行方法。