Vue 组件from,Props (defineProps) ,Emits, 插槽<slot/>(个人记录-4)

组件

目前为止,我们只使用了单个组件。真正的 Vue 应用往往是由嵌套组件创建的。父组件可以在模板中渲染另一个组件作为子组件。要使用子组件,我们需要先导入它:

import ChildComp from './ChildComp.vue'

然后我们就可以在模板中使用组件,就像这样:

<ChildComp />

例:

<script setup>
import ChildComp from './ChildComp.vue'
</script>

<template>
  <ChildComp />
</template>


  <!-- ChildComp.vue -->

<template>
  <h2>A Child Component!</h2>
</template>
Props (defineProps)

子组件可以通过 props 从父组件接受动态数据。首先,需要声明它所接受的 props:

<!-- ChildComp.vue -->
<script setup>
const props = defineProps({
  msg: String
})
</script>

父组件可以像声明 HTML attributes 一样传递 props。若要传递动态值,也可以使用 v-bind 语法

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

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

<template>
  <ChildComp :msg='greeting' />
</template>

<!-- ChildComp.vue -->
<script setup>
const props = defineProps({
  msg: String
})
</script>

<template>
  <h2>{{ msg || 'No props passed yet' }}</h2>
</template>
Emits

除了接收 props,子组件还可以向父组件触发事件:

<script setup>
// 声明触发的事件
const emit = defineEmits(['response'])

// 带参数触发
emit('response', 'hello from child')
</script>

emit() 的第一个参数是事件的名称。其他所有参数都将传递给事件监听器。

父组件可以使用 v-on 监听子组件触发的事件——这里的处理函数接收了子组件触发事件时的额外参数并将它赋值给了本地状态:

<ChildComp @response="(msg) => childMsg = msg" />

例:

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

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

<template>
  <ChildComp @response="(msg) => childMsg = msg" />
  <p>{{ childMsg }}</p>
</template>


<!-- ChildComp.vue -->

<script setup>
const emit = defineEmits(['response'])

emit('response', 'hello from child')
</script>

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

插槽

除了通过 props 传递数据外,父组件还可以通过插槽 (slots) 将模板片段传递给子组件:

<ChildComp>
  This is some slot content!
</ChildComp>

在子组件中,可以使用  元素作为插槽出口 (slot outlet) 渲染父组件中的插槽内容 (slot content):

<!-- 在子组件的模板中 -->
<slot/>

 插口中的内容将被当作“默认”内容:它会在父组件没有传递任何插槽内容时显示:

<slot>Fallback content</slot>

例:

<!-- ChildComp.vue -->
<template>
  <slot>Fallback content</slot>
</template>

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

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

<template>
  <ChildComp></ChildComp>
</template>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值