子组件
<template>
<p>{
{
msg}}</p>
</template>
<script>
import {
ref,reactive,onMounted} from 'vue'
export default {
name: "childrenComponent",
setup(){
const msg = ref("我是消息");
const changeMsg = ()=>{
msg.value = "我是更新后的消息"
}
return{
msg,
changeMsg
}
}
}
</script>
父组件
<template>
<childrenComponent ref="childrenComponentRef"></childrenComponent>
<button @click="handleChild"></button>
</template>
<script>
import childrenComponent from './childrenComponent.vue'
export default {
name: "parentComponent",
components:{
childrenComponent},
setup(){
const childrenComponentRef= ref(null); //定义子组件ref
//或者
//泛型默认值语法<T = any>
// type Ref<T = any> = {
// value : T
// }
// const childrenComponentRef:Ref<div | null> = ref(null);
const handleChild= ()=>{
childrenComponentRef.value.changeMsg();
}
return{
childrenComponentRef,
handleChild
}
}
}
</script>
另一种写法:
子组件,在script标签加上 ts(typescript), setup语法糖,用defineExpose暴露属性或方法
<template>
<p>{
{
msg}}</p>
</template>
<script lang="ts" setup>
import {
ref,reactive,onMounted} from 'vue'
const msg = ref("我是消息");
const changeMsg = ()=>{
msg.value = "我是更新后的消息"
}
defineExpose({
changeMsg
})
</script>
父组件
<template>
<childrenComponent ref="childrenComponentRef"></childrenComponent>
<button @click="handleChild"></button>
</template>
<script lang="ts" setup>
import childrenComponent from './childrenComponent.vue'
const childrenComponentRef= ref(null); //定义子组件ref
//或者 const childrenComponentRef:Ref<div | null> = ref(null);
const handleChild= ()=>{
childrenComponentRef.value.changeMsg();
}