1. 程式人生 > 其它 >vue3:子元件向父元件傳送資料([email protected])

vue3:子元件向父元件傳送資料([email protected])

一,編寫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

說明:作者:劉巨集締 郵箱: [email protected]

二,測試效果:

按鈕是子元件的元素,點選後能向父元件傳送訊息,如圖: 點選後,父元件收到訊息後進行響應:

三,檢視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