1. 父传子
基本上和Vue2中一样,只是需要用defineProps定义,下面举个例子直观地感受一下。
父组件中
<script setup>
import {reactive, ref} from "vue";
import SonView from "@/components/sonView.vue";
const type=ref('free')
const obj=reactive({
age:18,
content:'内容'
})
</script>
<template>
<div>
<son-view :type="type"></son-view>
<son-view></son-view> //检验默认值效果
<son-view :obj="obj"></son-view>
<son-view v-bind="obj"></son-view> //上一条语句的不同写法
</div>
</template>
<style scoped>
</style>
子组件中
<script setup>
// const props=defineProps(['type'])
const props = defineProps({
type: {
type: [Number, String],
default: 'son'
},
// obj:{
// type:[Object]
// }
obj: [Object],
age: [Number],//这里把obj里的age单独拿出来了
content: {
type: [String],
default: '默认'
}
})
</script>
<template>
<div>
{{ props.type }}
{{ props.obj }}
{{ props.age }}
</div>
</template>
<style scoped>
</style>
2.子传父
需要用defineEmits,有两种方法,下边是举例。
父组件中,和Vue2一样,自定义一个方法。
<script setup>
function fromSons(data){
console.log(data)
}
</script>
<templete>
<son-view @fromSon="fromSons"></son-view>
<template>
子组件中,有下面两种方法传参
//方法一
<button @click="$emit('fromSon',{id:123})">子传父</button>
//方法二
<button @click="toFather">toFather</button>
<script setup>
const emit=defineEmits(['fromSon'])
function toFather(){
emit('fromSon',{id:456})
}
</script>