vue3父子组件传参(setup语法糖写法)

41 篇文章 3 订阅
7 篇文章 0 订阅

1、父传子

父页面

<template>
  //传递参数
  <Test :userType="userType"></Test>
</template>
<script setup>
//引入子组件
import Test from '@/components/test/index.vue'
import { ref } from 'vue'

// 定义要给子组件传递的参数
const userType = ref('admin')
</script>

子组件

<script setup>
import { defineProps } from 'vue'

//周期函数
onMounted(() => {
	//打印父组件传递的值
  console.log(props.userType, 'userType')
})

//定义参数 已经选中的ITEMID
const props = defineProps({
  userType: {
    type: String, //参数类型
    default: String, //默认值
    required: true, //是否必须传递
  }
})
</script>

2、子传父

父页面

//接收子组件定义的事件
<Test @userName="userName"></Test>
// 接收子组件传递的参数
function userName(value) {
	//打印子组件传递的事件
  console.log(value, 'value')
}
//子组件
<template>
  <el-button type="danger" @click="clickEmit">点击传参</el-button>
</template>

子组件

<script setup>
import { ref, defineEmits } from 'vue'

// 定义一个参数
const userName = ref('阿凡')

// 定义emit
const emits = defineEmits(['userName'])

// 点击传参
function clickEmit() {
  /**
   * 第一个参数 -> 事件名称
   * 第二个参数--->要传递的值
   * **/
  emits('userName', userName.value)
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值