Vue3父子组件通信

2021-10-21 15:06:16 浏览数 (1)

子组件

代码语言:javascript复制
<template>
    <h1 @click="childClick">{{ title }}</h1>
    <button @click="updateFunc">修改父组件传递的值</button>
</template>

<script setup>
import { defineProps, defineEmits, defineExpose } from "vue"
defineProps({
    //定义子组件需要接收的值
    title: {
        type: String,
        default: ""
    }
})

//向父组件传递子组件的值和方法
defineExpose({
    childValue: "子组件的值",
    childFunc() {
        console.log("子组件的方法")
    }
})

// 注册事件
const emit = defineEmits(["myClick", "update:title"])

// 传给父组件的值
const childClick = () => {
    emit("myClick", "子组件通过事件传给父组件的参数")
}

//修改父组件传的值
const updateFunc = () => {
    emit("update:title", "子组件修改的新标题")
}

</script>

父组件

代码语言:javascript复制
<template>
    <child v-model:title="title" @myClick="getChild" ref="childRef" />
</template>
<script setup>
import { ref, onMounted } from "vue"
import child from "@/components/child.vue"
//传给子组件的值
const title = ref("传给子组件的title")

//通过事件接收子组件传递的值
const getChild = (e) => {
    console.log(e)
}

// 获取子组件的值和方法
const childRef = ref(null)
onMounted(() => {
    console.log(childRef.value.childValue)
    childRef.value.childFunc()
})
</script>

0 人点赞