Vue3——setup语法糖父子之间传值

1.父传子

父组件(传的值和传的方法)

<template>
  <view>
     引入组件无需注册
    <Counter :sex="sex @FatherMethod="FatherMethod"/>
  </view>
</template>
<script setup>
import Counter from "../../components/Counter.vue";
import { ref } from "vue";
传的值
const sex = ref('男')
传的方法
function FatherMethod(){
  console.log('这是FatherMethod');
}
</script>

子组件(使用父组件传的值和调用父组件的方法)

<template>
  <view>
    我是子组件
    <view class="button" @tap="onAdd">ADD</view>
    <view >我是父组件传过来的:{{sex }}</view>
  </view>
</template>
<script setup>
import { ref,toRefs } from "vue";
调用父组件的方法
const emits = defineEmits(["FatherMethod"]);
const onAdd = () => {
	emits("FatherMethod");
};
 使用传过来的值
const  props = defineProps(["sex"]);
or
const props = defineProps({
  sex:String
});
const {sex} =toRefs(props)
</script>

2.子传父

父组件(使用子组件传的值和调用子组件的方法)

使用子组件的方法
<template>
  <view>
   <div @click="sonMethod">子传父</div>
   <Counter ref="Childs"/>
  </view>
</template>
<script setup>
//声明子组件
const Childs = ref(null);
const sonMethod = () => {
	//子组件.value.方法
	Childs.value.ChildMethod();
};
</script>


接收子组件传过来的值
<template>
  <div >
  我是父组件
  <!-- clickChild是子组件绑定的事件,click是父组件接受方式 -->
   <Counter @toFather="sourceSon"></Child>
 <p>子组件传递的值是 {{result}}</p>
 </div>
</template>
 
<script setup>
import Counter from "../../components/Counter.vue";
import {ref} from 'vue'
const result=ref('')
const sourceSon=(val)=>{
  result.value=val.name
}
</script>

子组件(传的值和传的方法)

子组件传给父组件的方法
const ChildMethod = () => {
	console.log('嗨害嗨,我是子组件');
};
//暴露出去
defineExpose({
	ChildMethod
})


子组件给父组件传值
<template>
  <view>
    <view @click="toFather">toFather</view>
  </view>
</template>
<script setup>
const emits1 = defineEmits(["toFather"]);
const toFather= () => {
    let data={
      name:'yy'
     }
	emits1("toFather",data);
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值