VUE父传子,子传父

父传子,子传父,本质上都是父亲传递给儿子,只不过如果想要儿子回传数据,那么父亲就事先传递个自己的方法给儿子,儿子接收到这个方法,进行调用,把值传给父亲

父:

复制代码
<template>
  <div class="father">
    <h3>父组件</h3>
        车: {{car}}
        <!-- 父传子在子组件上通过属性绑定要传递值carFromFather -->
         <Child :carFromFather="car" :sonSendToyToFather="getToyFromSon"/>
        <!-- 子传父实际上是子组件触发父组件中事先定义好的方法,同样是通过属性绑定进行交互 -->
        <h3 v-if="toy">儿子给的玩具:{{toy}}</h3>
  </div>
</template>

<script setup lang="ts" name="Father">
 import Child from "./Child.vue";
 import { ref } from 'vue'
 let car=ref('奔驰')
 let toy=ref()

 //子传父,提前定义好方法,
 //子传父的本质还是把父定义的方法传递给子,子接收到函数后调用一下,通过父的函数把数据传递给父
function getToyFromSon(value:string){
   toy.value=value
}

</script>

<style scoped>
    .father{
        background-color:rgb(165, 164, 164);
        padding: 20px;
        border-radius: 10px;
    }
</style>
复制代码

子:

复制代码
<template>
  <div class="child">
    <h3>子组件</h3>
    玩具:{{toy}} <br/>
    父给的车: {{carFromFather}} <br/>
    <!-- <input type="button" @click="sonSendToyToFather" value="把玩具给父亲"> -->
    <button @click="sonSendToyToFather(toy)">把玩具给父亲</button>
  </div>
</template>

<script setup lang="ts" name="Child">
  import { ref } from 'vue'
 let toy=ref('奥特曼')
 //父传子接收用defineProps接收绑定的同名属性值来,接收的可以是值,也可以是方法
 defineProps(["carFromFather","sonSendToyToFather"])

 
</script>

<style scoped>
    .child{
        background-color: skyblue;
        padding: 10px;
        box-shadow: 0 0 10px black;
        border-radius: 10px;
    }
</style>
复制代码

 

posted @   关键步就几步  阅读(49)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示