Vue3 组件间通信实战

246 阅读1分钟

在 Vue3 中,各个功能被拆分成了单个模块,变成使用起来需先引入,后使用,无法像之前 Vue2 一样。但是组件间通信的思想是不变的,变的是 API 调用的方式。

在开始之前,需要有 Vue 2 的组件间通信基础知识,如果还没掌握的同学,可以移步 Vue 组件间通信方式 先学习,然后再学习本篇,就会轻车熟路。

本次实战基于脚手架 @vue/cli 4.5.17 版本创建, Vue 版本为3.2.37

1. 父组件向子组件传值

新建一个 Test 的文件夹,

Test 文件夹下新建一个 Test.vue 文件。

Test 文件夹下建一个 components 文件夹,用来存放子组件。

在 components 文件夹新建一个  .vue 文件,我这命名为 TestItem

向 Test.vue 添加代码

<template>
  <div>
    <test-item text="小忆技术体验设计团队"/>
  </div>
</template>

<script setup>
  import TestItem from '@/views/Test/components/TestItem'
</script>

向 TestItem.vue 添加代码

这里我们需要引入 Vue3 里的 defineProps 来定义以前的Props。 剩下的就跟以前的语法一样。

<template>
  <div>
    <p>{{ text }}</p>
  </div>
</template>

<script setup>
import { defineProps } from 'vue'

defineProps({
  text: {
    typeString,
    default''
  }
})
</script>

2. 子组件向父组件传值

修改 TestItem.vue 代码

这里我们需要引入 Vue3 里的 defineEmits 来定义以前的 emit。 剩下的就跟以前的语法一样。

<template>
  <div>
    <p>{{ text }}</p>
    <button @click="handleBtnClick">click</button>
  </div>
</template>

<script setup>

import { defineProps, defineEmits } from 'vue'

defineProps({
  text: {
    typeString,
    default''
  }
})

const handleBtnClick = () => {
  defineEmits(['fetch'])
}
</script>

运行后点击按钮后会报错,原因是不能直接像 defineProps 这样直接使用,必须赋值给一个常量。

修改 TestItem.vue 代码

<template>
  <div>
    <p>{{ text }}</p>
    <button @click="handleBtnClick">click</button>
  </div>
</template>

<script setup>

import { defineProps, defineEmits } from 'vue'

defineProps({
  text: {
    typeString,
    default''
  }
})

const emit = defineEmits(['fetch'])

const handleBtnClick = () => {
  emit('fetch''xytxd')
}
</script>

修改 Test.vue 代码

<template>
  <div>
    <test-item text="小忆技术体验设计团队"
               @fetch="handleFetch"
    />
    <p>子组件传过来的值: {{res}}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import TestItem from '@/views/Test/components/TestItem'

const res = ref('')

const handleFetch = n => {
  res.value = n
}
</script>

到此,运行后,点击按钮,父组件成功接收到了子组件传过来的值。

扫码_搜索联合传播样式-标准色版.png