【精品】vue3中setup语法糖下父子组件之间的通信

时间:2022-10-10 15:15:00

准备工作

在router文件夹中创建index.ts文件:

import {createRouter, createWebHashHistory} from 'vue-router'
import Father from '../views/Father.vue'

const routes = [
    {
        path: '/',
        name: "Father",
        component: Father
    },
    {
        path: '/Son',
        name: 'Son',
        component: () => import('../views/Son.vue')
    }
]
const router = createRouter({
    history: createWebHashHistory(),
    routes
})
export default router

父传子:

  • 第一步:Father.vue
<template>
  <h2>父组件</h2>
  <hr>
  <Son :num="num" :arr="array" ></Son>
</template>

<script lang="ts" setup>
import {ref} from 'vue'
import Son from "./Son.vue";

let num = ref(6688)
let array = ref([11, 22, 33, 44])
</script>
  • 第二步:Sun.vue
<template>
  <h2>子组件</h2>
  {{props.num}}--{{props.arr}}
</template>

<script lang="ts" setup>
let props = defineProps({
  num: Number,
  arr: {
    type: Array,
    default: () => [1, 2, 3, 4]
  }
})
</script>

子传父:

  • 第一步:Sun.vue
<template>
  <h2>子组件</h2>
  <button @click="sendMsg">向父组件传递数据</button>
</template>

<script lang="ts" setup>
import {ref} from 'vue'

const emit = defineEmits(["son_sendMsg"]);
const msg = ref("子组件传递给父组件的数据")

function sendMsg() {
  emit("son_sendMsg", msg.value)
}
</script>
  • 第二步:Father.vue:
<template>
  <h2>父组件</h2>
  {{ message }}
  <hr>
  <Son @son_sendMsg="fun"></Son>
</template>

<script lang="ts" setup>
import {ref} from 'vue'
import Son from "./Son.vue"

let message = ref("")
function fun(msg) {
  message.value = msg
}
</script>