在setup语法糖中父子组件的写法有两种
1、第一种用defineProps和defineEmits
(1) 父组件传值给子组件,子组件用defineProps接收
父组件代码:
<template>
<div class="home">
<HelloWorld :msg="num" @change="change" />
</div>
</template>
<script lang="ts" setup>
import {onMounted, ref} from 'vue';
//components
import HelloWorld from '@/components/HelloWorld.vue';
//变量
const num=ref<number>(0);
</script>
HelloWorld 子组件代码:
<template>
<div class="hello">
<h1>我是hello页面</h1>
<p>{{msg}}</p>
</div>
</template>
<script lang="ts" setup>
import {defineProps,defineEmits} from 'vue'
const prop=defineProps({
msg:Number
})
</script>
<style scoped>
</style>
(2) 子组件用 defineEmits 传递给父组件信息
HelloWorld子组件
<template>
<div class="hello">
<h1>我是hello页面</h1>
<p>{{msg}}</p>
<button @click="add">增加</button>
</div>
</template>
<script lang="ts" setup>
import {defineProps,defineEmits} from 'vue'
const prop=defineProps({
msg:Number
})
const emit=defineEmits(['change'])
const add=()=>{
console.log(prop.msg);
emit('change','1234')
}
</script>
<style scoped>
</style>
父组件
<template>
<div class="home">
<HelloWorld :msg="num" @change="change" />
<child ref="sonRef"></child>
</div>
</template>
<script lang="ts" setup>
import {onMounted, ref} from 'vue';
//components
import HelloWorld from '@/components/HelloWorld.vue';
//变量
const num=ref<number>(0);
//方法
const change=(val:any)=>{
num.value++
}
</script>
2、父组件使用ref获取子组件的实例,从而获取子组件的变量和方法。但是要注意子组件无论是方法还是变量都要用defineExpose暴露出去,否则父组件是接收不到的。
子组件:
<template>
<div class="child1">
<p>我是child1页面</p>
</div>
</template>
<script lang="ts" setup>
import {ref,defineExpose} from 'vue'
//变量
const msg=ref<string>('1245');
//方法
const sonMethod=()=>{
console.log('我是子页面的方法');
}
defineExpose({
msg,
sonMethod
})
</script>
<style scoped>
</style>
父组件:
<template>
<div class="home">
<child ref="sonRef"></child>
<button @click="getSon">父组件获取子组件的实例</button>
</div>
</template>
<script lang="ts" setup>
import {onMounted, ref} from 'vue';
//components
import child from '../components/ChildOne.vue'
//子组件的类型
const sonRef=ref<InstanceType<typeof child>>();
const getSon=()=>{
console.log(sonRef.value?.msg);
sonRef.value?.sonMethod();
}
</script>