欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > Vue3 父子组件传值

Vue3 父子组件传值

2025/6/10 0:39:54 来源:https://blog.csdn.net/weixin_43204464/article/details/144209271  浏览:    关键词:Vue3 父子组件传值

也不用看我下面的解说,直接看代码,简单明了。只是个用法而已。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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词