vue3-组件通信

1. 父传子-defineProps

父组件:

<script setup>
import {
    ref } from 'vue'
  import SonCom from '@/components/Son-com.vue'
  const message = ref('parent')

</script>

<template>
 <div></div>
 <SonCom car="沃尔沃" :message="message"></SonCom>
</template>

<style>
</style>

子组件接收:

<script setup>
// 子组件
const props = defineProps({
   
  car: String,
  message: String
})

</script>

<template>
 <div class="son">我是子组件</div>
 <div>{
   {
    car }}</div>
 <div>{
   {
    message }}</div>
</template>

<style scoped>
.son{
   
  width: 100px;
  height: 200px;
  background-color: #a72b2b;
}
</style>

解释:
在这里插入图片描述

2. 子传父 - defineEmits

子组件:

<script setup>
// 子组件
const props = defineProps({
   
  car: String,
  message: String
})

// 子传父
const emit = defineEmits(['updateMessage'])
const updateMsg = () =>{
   
  emit('updateMessage', props.message + 'is update')
}

</script>

<template>
 <div class="son">我是子组件</div>
 <div>{
   {
    car }}</div>
 <div>{
   {
    message }}</div>
 <button @click="updateMsg">修改message</button>
</template>

<style scoped>
.son{
   
  width: 100px;
  height: 200px;
  background-color: #a72b2b;
}
</style>

父组件:

<script setup>
import {
    ref } from 'vue'
  import SonCom from '@/components/Son-com.vue'
  const message = ref('parent')

  // 修改消息
  const updateMessage = (msg) => {
    message.value = msg}

</script>

<template>
 <div>我是父组件</div>
 <SonCom car="沃尔沃" :message="message" @updateMessage="updateMessage"></SonCom>
</template>

<style>
</style>

解释:
在这里插入图片描述

3. 跨层传递 - provide和inject

上层组件(祖组件):

  // 跨层传递
  // 传递普通类型
  provide('upMsg', '上层消息')

  // 传递响应式类型
  const upObj = ref({
    name: 'jingjing'})
  provide('upObj', upObj)

  // 传递方法:修改响应式类型
  const updateObj = (newName) => {
    upObj.value.name = newName}
  provide('updateObj', updateObj)

下层组件(孙组件):

// 接收上层数据
// 接收普通类型
const upMsg = inject('upMsg')
// 接收响应类型
const upObj = inject('upObj')
// 接收方法
const updateObj = inject('updateObj')

案例:
在这里插入图片描述

相关推荐

  1. Vue3父子组件通信

    2024-01-23 00:48:01       62 阅读
  2. Vue3组件通信相关内容整理

    2024-01-23 00:48:01       58 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-23 00:48:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-23 00:48:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-23 00:48:01       82 阅读
  4. Python语言-面向对象

    2024-01-23 00:48:01       91 阅读

热门阅读

  1. C++中函数的默认参数(缺省参数)

    2024-01-23 00:48:01       54 阅读
  2. 计算机网络复试

    2024-01-23 00:48:01       53 阅读
  3. C++ 类和对象 知识笔记

    2024-01-23 00:48:01       51 阅读
  4. 函数式编程

    2024-01-23 00:48:01       49 阅读
  5. 53.最大子数组和(前缀和、动态规划,C解法)

    2024-01-23 00:48:01       61 阅读
  6. 【算法详解】力扣415.字符串相加

    2024-01-23 00:48:01       73 阅读