vue3组件通信--props

目录

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

1.父传子

父组件(FatherComponent.vue):

html 复制代码
<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):

html 复制代码
<script setup>
const props = defineProps(['money','updateMoney'])
</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来接受的数据是只读的,子组件不能再组件内部更改它。

比如,不能下面这样写,否则控制台会报错:

html 复制代码
<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>

2.子传父

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

html 复制代码
<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):

html 复制代码
<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>
相关推荐
盛夏绽放几秒前
接口验证机制在Token认证中的关键作用与优化实践
前端·node.js·有问必答
zhangxingchao17 分钟前
Jetpack Compose 之 Modifier(中)
前端
JarvanMo17 分钟前
理解 Flutter 中 GoRouter 的context.push与context.go
前端
pe7er23 分钟前
使用 Vue 官方脚手架创建项目时遇到 Node 18 报错问题的排查与解决
前端·javascript·vue.js
星始流年26 分钟前
前端视角下认识AI Agent
前端·agent·ai编程
pe7er30 分钟前
使用 types / typings 实现全局 TypeScript 类型定义,无需 import/export
前端·javascript·vue.js
CH_Qing31 分钟前
【udev】关于/dev 设备节点的生成 &udev
linux·前端·网络
小诸葛的博客35 分钟前
gin如何返回html
前端·html·gin
islandzzzz42 分钟前
(第二篇)HMTL+CSS+JS-新手小白循序渐进案例入门
前端·javascript·css·html
喝拿铁写前端44 分钟前
前端实战优化:在中后台系统中用语义化映射替代 if-else,告别魔法数字的心智负担
前端·javascript·架构