vue3:子组件向父组件发送数据(vue@3.2.26)

vue

一,编写js代码

1,Parent.vue

<template>

<div>

<Child @eventParent="receiveMessage"></Child>

</div>

</template>

<script>

import Child from './Child'

export default {

name: "Parent",

components: {

Child,

},

setup() {

//接收消息

const receiveMessage = (data) => {

let msg="code:"+data.code+";msg:"+data.msg;

alert(msg);

}

return {

receiveMessage,

}

}

}

</script>

<style scoped>

</style> 

2,Child.vue

<template>

<div>

<button @click="sendToParent">向父组件传递消息</button>

</div>

</template>

<script>

export default {

name: "Child",

setup (props,{emit}) {

//向父组件发送消息

const sendToParent = () => {

let msg = {

code:1,

msg:"这是子组件发送的数据",

}

emit('eventParent',msg)

}

return {

sendToParent,

}

}

}

</script>

<style scoped>

</style>

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,测试效果:

按钮是子组件的元素,点击后能向父组件发送消息,如图:

 

点击后,父组件收到消息后进行响应:

三,查看vue的版本:

liuhongdi@lhdpc:/data/vue/demo1$ npm list vue

demo1@0.1.0 /data/vue/demo1

├─┬ @vue/cli-plugin-babel@4.5.15

│ └─┬ @vue/babel-preset-app@4.5.15

│ └── vue@3.2.26 deduped

├─┬ element-plus@1.2.0-beta.6

│ ├─┬ @element-plus/icons-vue@0.2.4

│ │ └── vue@3.2.26 deduped

│ ├─┬ @vueuse/core@7.4.1

│ │ ├─┬ @vueuse/shared@7.4.1

│ │ │ └── vue@3.2.26 deduped

│ │ ├─┬ vue-demi@0.12.1

│ │ │ └── vue@3.2.26 deduped

│ │ └── vue@3.2.26 deduped

│ └── vue@3.2.26 deduped

└─┬ vue@3.2.26

└─┬ @vue/server-renderer@3.2.26

└── vue@3.2.26 deduped

以上是 vue3:子组件向父组件发送数据(vue@3.2.26) 的全部内容, 来源链接: utcz.com/z/376365.html

回到顶部