VUE3.x教程(八)组件传递

1、Props

props用于父组件向子组件传值。

子组件通过props从父组件索取数据,父组件调用子组件时,将props中定义的参数传入即可。

①子组件 ChildComp.vue

<script setup>
// defineProps() 是一个编译时宏,并不需要导入。一旦声明,msg prop 就可以在子组件的模板中使用。
const props = defineProps({
  msg: String
})
</script>

<template>
  // msg不为空则直接显示,否则显示后面的
  <h2>{{ msg || 'No props passed yet' }}</h2>
</template>

②父组件中调用子组件,并传参

<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'

const greeting = ref('Hello from parent')
</script>

<template>
  // :msg将msg绑定到greeting
  <ChildComp :msg="greeting" />
  // 将msg的值直接传给子组件
  <ChildComp msg="greeting" />
</template>

③返回结果为

2、Emits

emits用于子组件向父组件传值。

由于VUE的机制原因,子组件不能直接向父组件传值,需要通过触发事件向父组件传值。

①子组件 ChildComp.vue

<script setup>
// defineEmits用来声明emit事件,名为response
const emit = defineEmits(['response'])

// 使用emit()将response事件和数据,传递给父组件
emit('response', 'hello from child')
</script>

<template>
  <h2>Child component</h2>
</template>

②父组件调用子组件,并响应事件

<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'

const childMsg = ref('No child msg yet')
</script>

<template>
  // 绑定事件@response,将从子组件接收的数据赋值给childMsg
  <ChildComp @response="(msg) => childMsg = msg" />
  // 子组件显示完成后,显示childMsg的内容
  <p>{{ childMsg }}</p>
</template>

③返回结果为

3、Slots

Slots用于父组件向子组件传递模板片段

①子组件 ChildComp.vue

<template>
  <slot>Fallback content</slot>
</template>

②父组件 

<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'

const msg = ref('from parent')
</script>

<template>
  // 将Message: {{ msg }}传给子组件
  <ChildComp>Message: {{ msg }}</ChildComp>
</template>

③返回结果为

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值