前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue3父子组件通信

Vue3父子组件通信

作者头像
明知山
发布2021-10-21 15:06:16
1.4K0
发布2021-10-21 15:06:16
举报
文章被收录于专栏:前端开发随笔

子组件

代码语言: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>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/10/19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 子组件
  • 父组件
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档