一:defineProps()在vue3中可以实现父子组件通信,组件内部不需要引入defineProps。
案例子组件向父组件传值如下:
1:父组件
<template>
<div>
<el-button @click="testClick">测试defineProps</el-button>
<test-plate :sonTitle="fatherTitle" :sonNum="fatherNum"></test-plate>
</div>
</template>
<script setup>
import testPlate from './componts/test.vue'
import {ref} from "vue"
const fatherTitle = ref('hello')
const fatherNum = ref(1)
const testClick = ()=>{
fatherTitle.value = '哈哈哈',
fatherNum.value = 2
}
2:子组件
<template>
<div>
<p>{{props.sonTitle}}---{{props.sonNum}}</p>
</div>
</template>
<script setup>
let props = defineProps({
sonTitle:{
type:String,//接受的数据类型
default:'默认参数',//接受默认数据
},
sonNum:{
type:Number,
default:0
}})
</script>
当然子组件也可以这样写
let props = defineProps(["sonTitle",'sonNum'])
需要注意的是:子组件只能读取父组件传递过来的数据,无法修改数据
二:defineEmits()接受自定义事件,可以实现子组件给父组件传递数据
具体形式是
// 子组件:创建自定义事件,传递数据
const emit = defineEmits(['自定义事件']);
emit('自定义事件', 数据1, 数据2);
// 父组件:绑定自定义事件,接收数据
<组件标签 @自定义事件="函数名"></组件标签>
const 函数名 = (参数1, 参数2) => {
console.log(参数1, 参数2);
}
案例:关闭子组件
1:子组件
<template>
<div>
<el-button @click="changeView">点我给父组件传值</el-button>
</div>
</template>
<script setup>
import { ref } from "vue"
const childView = ref(false)
const $emit = defineEmits(['changeChild'])
const changeView = ()=>{
$emit('changeChild',childView)
}
</script>
2:父组件
<template>
<div>
<test-plate v-if="showView" @changeChild="changeView"></test-plate>
</div>
</template>
<script setup>
import testPlate from './componts/test.vue'
import {ref} from "vue"
const showView = ref(true)
const changeView = (val)=>{
console.log('val===',val)
showView.value = val.value
}
</script>
子组件使用自定义事件后,父组件中的事件函数会自动执行