父组件
父组件跟vue2.0没有变化,通过 :childName="childName",传值给子组件;通过@noticeParent="noticeParent" 函数接收子组件值,参数value即为子组件穿过来的值
<template>
<h3>父组件</h3>
<p>响应式:{{data.name}}</p>
<p>非响应式:{{name}}{{age}}</p>
<propsChild :childName="childName" @noticeParent="noticeParent"></propsChild>
</template>
<script setup lang="ts">
import {reactive, toRefs} from 'vue'
import propsChild from './propsChild.vue'
const data= reactive({
name:'父',
age:12
})
let name = '父'
let age = 10;
let childName = '传给子组件的值'
const noticeParent=(value:string)=>{
data.name = value;
name = '子改父';
age = 12;
}
</script>
<style lang="scss">
</style>
子组件
子组件是通过defineProps接收父组件值,通过defineEmits向父组件传递值
<template>
<h4>子组件</h4>
<p>{{childName}}</p>
<button @click="noticeParent">传值父组件</button>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
const emit = defineEmits({
noticeParent:null
})
const props=defineProps<{
childName: string
}>()
const parentValue = '反馈都组件的值'
const noticeParent=()=>{
emit('noticeParent',parentValue)
}
onMounted(()=>{
console.log(props)
})
</script>
<style lang="scss">
</style>