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>
相关推荐
水银嘻嘻1 小时前
08 web 自动化之 PO 设计模式详解
前端·自动化
Zero1017133 小时前
【详解pnpm、npm、yarn区别】
前端·react.js·前端框架
&白帝&3 小时前
vue右键显示菜单
前端·javascript·vue.js
Wannaer3 小时前
从 Vue3 回望 Vue2:事件总线的前世今生
前端·javascript·vue.js
羽球知道4 小时前
在Spark搭建YARN
前端·javascript·ajax
光影少年4 小时前
vue中,created和mounted两个钩子之间调用时差值受什么影响
前端·javascript·vue.js
青苔猿猿4 小时前
node版本.node版本、npm版本和pnpm版本对应
前端·npm·node.js·pnpm
一只码代码的章鱼5 小时前
Spring的 @Validate注解详细分析
前端·spring boot·算法
zimoyin5 小时前
Kotlin 协程实战:实现异步值加载委托,对值进行异步懒初始化
java·前端·kotlin
cdcdhj5 小时前
vue用通过npm的webpack打包编译,这样更适合灵活配置的项目
vue.js·webpack·npm