也不用看我下面的解说,直接看代码,简单明了。只是个用法而已。props变成了 defineProps
$emit变成了defineEmits
1.父传子
简单介绍语法怎么使用
用defineProps接收一个数组,里面就是父组件传的值,直接用到模板里就可以
defineProps(['message'])
2.子传父
$emit变成了 const emit = defineEmits(['sendValue']) //sendValue是父组件自定义方法
const handler = () =>{
emit('sendValue',value) //value是传递给父组件的值
}
3.代码
father.vue
<template><p>{{ fatherData }}</p><el-button type="primary" @click="changeChild">父组件按钮,点击修改子组件数据</el-button><!-- <father></father> --><child :message="fatherData" @sendValue="handleValue"></child>
</template><script lang="ts" setup>
import child from './components/child.vue';
import {ref,reactive} from 'vue'
const fatherData = ref('我是父组件初始数据')
const changeChild = () =>{fatherData.value = 'data'
}
//子组件修改父组件数据
const handleValue = (value) =>{fatherData.value = valueconsole.log(value,'value');}
</script><style></style>
2.child.vue
<template><p>{{ childData }}</p><p>{{ message }}</p><el-button type="primary" @click="changeFatherData">点击子组件修改父组件数据</el-button>
</template><script lang="ts" setup>
// 父传子import {ref} from 'vue'const childData = ref('初始子组件数据')defineProps(['message'])// 子传父const emit = defineEmits(['sendValue'])const changeFatherData = () =>{emit('sendValue','父组件数据已经被子组件修改了')}
</script><style></style>