vue3组件通信--props

119 阅读2分钟

最近在做项目的过程中发现,props父子通信忘的差不多了。下面写个笔记复习一下。

1.响应式Props结构

vue3.5以前的版本通过下面的这种方式结构出来的变量不是响应式的:

image.png 在 Vue 3.5 及以上版本,defineProps 会做一些特殊处理。当你在 <script setup> 代码块中解构 props 时,Vue 会自动把解构出的变量转换成对 props 对象的引用。这意味着,尽管你写的是解构语法,实际上访问的仍然是 props 对象的属性。因此,解构出的变量会保持响应式。

2.prop推荐的命名方式

父组件给子组件传递prop的时候,应该用kebab-case 形式来书写。

image.png 子组件用defineProps接受prop的时候,应该用camelCase 形式来书写:

image.png

3.父传子

父组件(FatherComponent.vue):

<script setup>
import ChildComponent from "@/components/ChildComponent.vue"
import { ref } from "vue"

const fatherMoney = ref(1000)
</script>

<template>
  <div class="bg-blue h-75 w-100 ma-auto">
    <h1 class="text-center">我是父组件</h1>
    <ChildComponent :money="fatherMoney"></ChildComponent>
  </div>
</template>

我们可以在子组件标签上写:money="fatherMoney"。意思就是把父亲的响应式变量fatherMoney给子组件,子组件在组件内部要用money来接受这个变量。 子组件(ChildComponent.vue):

<script setup>
const props = defineProps(['money'])
</script>

<template>
  <div class="bg-purple h-50 w-75 ma-auto">
    <h1 class="text-center">我是子组件</h1>
    <h3>父亲给我的钱:{{money}}元</h3>
  </div>
</template>

子组件<h3>父亲给我的钱:{{money}}元</h3>这一块儿,我们可以用props.money来渲染这个数据,也可以省略props,直接写money

注意,用props来接受的数据是只读的,子组件不能再组件内部更改它。 比如,不能下面这样写,否则控制台会报错:

<script setup>
const props = defineProps(['money'])

const updateMoney = () => {
  props.money = 100
}
</script>

<template>
  <div class="bg-purple h-50 w-75 ma-auto">
    <h1 class="text-center">我是子组件</h1>
    <h3>父亲给我的钱:{{money}}元</h3>
    <v-btn @click="updateMoney" class="text-white bg-blue">修改父亲给我的钱</v-btn>
  </div>
</template>

在这里插入图片描述

4.子传父

子组件向父组件发送数据,父组件需要定义一个方法,用来接受子组件发送的数据: 父组件(FatherComponent.vue):

<script setup>
import ChildComponent from "@/components/ChildComponent.vue"
import { ref } from "vue"

const fatherMoney = ref(1000)

const childToy = ref('')
const getToy = (value)=>{
  childToy.value = value
}
</script>

<template>
  <div class="bg-blue h-75 w-100 ma-auto">
    <h1 class="text-center">我是父组件</h1>
    <h3>儿子给我的玩具:{{childToy}}</h3>
    <ChildComponent :money="fatherMoney" :sendToy="getToy"></ChildComponent>
  </div>
</template>

:sendToy="getToy"意思就是,父组件给子组件传递了一个方法getToy,子组件要用方法sendToy,给父亲发送数据。 子组件(ChildComponent.vue):

<script setup>
import {ref} from "vue"

const props = defineProps(['money','sendToy'])

const toy = ref('奥特曼')
</script>

<template>
  <div class="bg-purple h-50 w-75 ma-auto">
    <h1 class="text-center">我是子组件</h1>
    <h3>父亲给我的钱:{{money}}元</h3>
    <v-btn @click="sendToy(toy)" class="text-white bg-blue">把玩具给父亲</v-btn>
    <h3>儿子的玩具:{{toy}}</h3>
  </div>
</template>

在这里插入图片描述