微网站功能介绍,搜索引擎优化的主要工作,建设网站需要提交什么资料,自己做企业网站服务器目录 1.父传子2.子传父 最近在做项目的过程中发现#xff0c;props父子通信忘的差不多了。下面写个笔记复习一下。 1.父传子
父组件#xff08;FatherComponent.vue#xff09;#xff1a;
script setup
import ChildComponent from /components/ChildComp… 目录 1.父传子2.子传父 最近在做项目的过程中发现props父子通信忘的差不多了。下面写个笔记复习一下。 1.父传子
父组件FatherComponent.vue
script setup
import ChildComponent from /components/ChildComponent.vue
import { ref } from vueconst fatherMoney ref(1000)
/scripttemplatediv classbg-blue h-75 w-100 ma-autoh1 classtext-center我是父组件/h1ChildComponent :moneyfatherMoney/ChildComponent/div
/template
我们可以在子组件标签上写:moneyfatherMoney。意思就是把父亲的响应式变量fatherMoney给子组件子组件在组件内部要用money来接受这个变量。 子组件ChildComponent.vue
script setup
const props defineProps([money,updateMoney])
/scripttemplatediv classbg-purple h-50 w-75 ma-autoh1 classtext-center我是子组件/h1h3父亲给我的钱{{money}}元/h3/div
/template子组件h3父亲给我的钱{{money}}元/h3这一块儿我们可以用props.money来渲染这个数据也可以省略props直接写money。
注意用props来接受的数据是只读的子组件不能再组件内部更改它。 比如不能下面这样写否则控制台会报错
script setup
const props defineProps([money])const updateMoney () {props.money 100
}
/scripttemplatediv classbg-purple h-50 w-75 ma-autoh1 classtext-center我是子组件/h1h3父亲给我的钱{{money}}元/h3v-btn clickupdateMoney classtext-white bg-blue修改父亲给我的钱/v-btn/div
/template 2.子传父
子组件向父组件发送数据父组件需要定义一个方法用来接受子组件发送的数据 父组件FatherComponent.vue
script setup
import ChildComponent from /components/ChildComponent.vue
import { ref } from vueconst fatherMoney ref(1000)const childToy ref()
const getToy (value){childToy.value value
}
/scripttemplatediv classbg-blue h-75 w-100 ma-autoh1 classtext-center我是父组件/h1h3儿子给我的玩具{{childToy}}/h3ChildComponent :moneyfatherMoney :sendToygetToy/ChildComponent/div
/template
:sendToygetToy意思就是父组件给子组件传递了一个方法getToy,子组件要用方法sendToy给父亲发送数据。 子组件ChildComponent.vue
script setup
import {ref} from vueconst props defineProps([money,sendToy])const toy ref(奥特曼)
/scripttemplatediv classbg-purple h-50 w-75 ma-autoh1 classtext-center我是子组件/h1h3父亲给我的钱{{money}}元/h3v-btn clicksendToy(toy) classtext-white bg-blue把玩具给父亲/v-btnh3儿子的玩具{{toy}}/h3/div
/template