Vue3:父子组件传参

一、父组件给子组件传参

父组件通过v-bind绑定要传给子组件的数据,在子组件中通过defineProps接收传过来的值

父组件:

<template>
  <Child :data="cMasterwork" :sMasterwork="sMasterwork"></Child>
</template>
<script setup lang="ts">
// 这里只需要引入即可使用组件,不需要注册
import Child from './child.vue'
import { reactive } from 'vue';
const cMasterwork = reactive<string[]>(['西游记','水浒传','三国演义','红楼梦'])
const sMasterwork = reactive<string[]>(['葫芦娃','七龙珠','喜羊羊与灰太狼','白雪公主'])
</script>

子组件:

TS接收参数

<template>
  <div v-for="(item,index) in data" :key="index">
    {{item}}
  </div>
  <div v-for="(item,index) in sMasterwork" :key="index">
    {{item}}
  </div>
</template>
<script setup lang="ts">
// TS接收参数的简易写法
defineProps<{
  data:string[],
  sMasterwork:string[],
}>()
</script>

如果不是ts

defineProps({
    data:Array
    sMasterwork:Array
})

TS独特的默认值提供方式

<template>
  <div v-for="(item,index) in data" :key="index">{{ item }}</div>
  <div v-for="(item,index) in sMasterwork" :key="index">{{ item }}</div>
</template>
<script setup lang="ts">
type Props = {
  data?: string[],
  sMasterwork?: string[]
}
withDefaults(defineProps<Props>(), {
  data: () => ['孙悟空', '白素贞'],
  sMasterwork: () => ['1', '2', '3']
})
</script>

二、子组件给父组件传参

通过defineEmits派发事件

子组件:

<template>
  <div>
    <button @click="sendData">传递数据给父组件</button>
  </div>
</template>
 
<script setup lang="ts">
import { reactive } from 'vue'
const list = reactive<number[]>([1, 2, 3])
const emit = defineEmits(['getChildData'])
const sendData = () => {
  emit('getChildData', list)
}
</script>

父组件:

<template>
  <Child @get-child-data="getChildData"></Child>
</template>
<script setup lang="ts">
// 这里只需要引入即可使用组件,不需要注册
import Child from './child.vue'
const getChildData = (list: number[]) => {
  console.log(list, '从子组件获取到的数据');
}
</script>

三、子组件给父组件暴露方法和属性

子组件:

子组件通过defineExpose暴露方法和属性出去

<template>
  <div class="child">子组件</div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
const list = reactive<number[]>([1, 2, 3])
const childEvents = () => {
  console.log('childEvents,子组件中的事件');
}
defineExpose({
  list,
  childEvents
})
</script>

父组件:

父组件通过ref获取子组件实例

<template>
  <Child ref="child"></Child>
</template>
<script setup lang="ts">
// 这里只需要引入即可使用组件,不需要注册
import Child from './child.vue'
import { ref, onMounted, Ref } from 'vue';

const child = ref(null) as Ref;

onMounted(() => {
  console.log(child.value.list);
  child.value.childEvents();
})
</script>

  • 12
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值