Vue3子传父

本文详细介绍了在Vue3中如何实现子组件向父组件传递数据的过程,通过一个具体的代码示例展示了如何使用`$emit`触发自定义事件,并在父组件中监听并接收来自子组件的数据。同时,还涉及到Vuex的使用,展示了如何在组件间共享状态。
摘要由CSDN通过智能技术生成

原文地址:Vue3子传父 - 简书

1.父组件

<template>
  <div class="home" @click="clik1">
    {{ $store.state.aaa }}
  </div>
  <about :data=name @clickFu = receive></about>
</template>

<script lang="ts">
import { defineComponent ,ref} from 'vue';
import about from './About.vue'
import { useStore } from 'vuex'
export default defineComponent({
  name: 'Home',
  components: {
    about
  },
  setup(){
    const store = useStore();
    const name = ref('小叶')
    function clik1(){
      store.commit('add',10)
    }
    function receive(e: any){
       console.log(e)
    }
    return{
      clik1,
      name,
      receive
    }
  }
});
</script>

2.子组件

<template>
  <div class="home" @click="clickSon">
    {{data}}
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'About',
  components: {
    
  },
  props:['data'],
  setup(props,context){
    console.log(props.data)//可以拿到父组件的数据
    function clickSon(){
      context.emit('clickFu','11111')
    }
    return{
      clickSon
    }
  }
});
</script>



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值