1 尽管存在 prop 和事件,有的时候你仍可能需要在 JavaScript 里直接访问一个子组件(例如,调用子组件的方法)。为了达到这个目的,你可以通过 ref 特性为这个子组件赋予一个 ID 引用。
2 $refs 只会在组件渲染完成之后生效,并且它们不是响应式的。这仅作为一个用于直接操作子组件的“逃生舱”——你应该避免在模板或计算属性中访问 $refs。
父组件
<template>
<div id="app">
<button @click="start">点击</button>
<Pirate ref="pirate" msg="加勒比海盗"/>
</div>
</template>
<script>
import Pirate from './components/Pirate.vue'
export default {
name: 'app',
components: {
Pirate
},
methods:{
start(){
this.$refs.pirate.hello();
}
}
}
</script>
<style>
</style>
子组件
<template>
<h3>
{{msg}}
</h3>
</template>
<script>
export default {
props: {
msg: {
type: String
}
},
methods: {
hello() {
console.log("子组件方法");
}
}
};
</script>
<style>
</style>
运行效果

