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 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一1 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球1 小时前
el-button按钮的loading状态设置
前端·javascript
kidding7231 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
无责任此方_修行中3 小时前
每周见闻分享:杂谈AI取代程序员
javascript·资讯
Σίσυφος19003 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库
学代码的小前端3 小时前
0基础学前端-----CSS DAY13
前端·css
dorabighead4 小时前
JavaScript 高级程序设计 读书笔记(第三章)
开发语言·javascript·ecmascript
css趣多多5 小时前
案例自定义tabBar
前端
姑苏洛言6 小时前
DeepSeek写微信转盘小程序需求文档,这不比产品经理强?
前端