Vue3 父子组件传值

也不用看我下面的解说,直接看代码,简单明了。只是个用法而已。props变成了 defineProps

$emit变成了defineEmits 

1.父传子

简单介绍语法怎么使用

用defineProps接收一个数组,里面就是父组件传的值,直接用到模板里就可以

defineProps(['message'])

2.子传父

$emit变成了 const emit = defineEmits(['sendValue'])  //sendValue是父组件自定义方法

const handler = () =>{

emit('sendValue',value) //value是传递给父组件的值

}

 3.代码

father.vue

<template>
    <p>{{ fatherData }}</p>
    <el-button type="primary" @click="changeChild">父组件按钮,点击修改子组件数据</el-button>
    <!-- <father></father> -->
    <child :message="fatherData" @sendValue="handleValue"></child>
</template>

<script lang="ts" setup>
import child from './components/child.vue';
import {ref,reactive} from 'vue'
const fatherData = ref('我是父组件初始数据')
const changeChild = () =>{
    fatherData.value = 'data'
}
//子组件修改父组件数据
const handleValue = (value) =>{
    fatherData.value = value
    console.log(value,'value');
    
}
</script>

<style>

</style>

2.child.vue

<template>
  <p>{{ childData }}</p>
  <p>{{ message }}</p>
  <el-button type="primary" @click="changeFatherData">点击子组件修改父组件数据</el-button>
</template>

<script lang="ts" setup>
// 父传子
  import {ref} from 'vue'
  const childData = ref('初始子组件数据')
  defineProps(['message'])

// 子传父
 const emit = defineEmits(['sendValue'])
 const changeFatherData = () =>{
    emit('sendValue','父组件数据已经被子组件修改了')
 }
</script>

<style>

</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值