vue3 组件基础

Zoella Lv3

基础

父传子

defineProps 是仅在 <script setup> 中可用的编译宏命令

1
2
3
4
5
<script setup>
defineProps(['title', 'content']);
</script>

<template>{{ title }}{{ content }}</template>

子传父

defineEmits 是仅在 <script setup> 中可用的编译宏命令

1
2
3
4
5
<script setup>
const emit = defineEmits('enlarge-text');

emit('enlarg-text'); // 抛出事件
</script>

slot 插槽

子组件:

1
2
3
4
5
6
<template>
<div class="child">
<span>123</span>
<slot />
</div>
</template>

父组件:

1
2
3
4
5
<template>
<child-component>
<span>hahaha<span>
</child-component>
</template>

子组件渲染结果为:

1
2
3
4
5
6
<template>
<div class="child">
<span>123</span>
<span>hahaha</span>
</div>
</template>

子组件标签

子组件有关闭标签

父组件可以子组件传递 slot 内容

1
<my-component></my-component>

子组件无关闭标签

父组件无法向子组件传递 slot 内容

1
<my-component />

动态组件

通过 component 组件,和 :is 属性切换动态组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<template>
<!-- 点击切换 tab -->
<button v-for="tab in tabs" @click="curTab = tab">
{{ tab }}
</button>
<!-- 动态组件 -->
<component :is="tabs[curTab]"></component>
</template>

<script setup>
import Home from './Home.vue';
import Posts from './Posts.vue';
import Archive from './Archive.vue';
import { ref } from 'vue';

const curTab = ref('Home'); // 初始展示 Home 组件

const tabs = {
Home,
Posts,
Archive
};
</script>

元素位置限制

某些元素对于放在其中的元素类型有限制:<ul>, <ol>, <table>, <select>

某些元素仅在特定元素中才会显示:<li>, <tr>, <option>

1
2
3
4
<table>
<!-- 自定组件在 <table> 中不生效 -->
<post-row></post-row>
</table>

解决方案(使用 is 属性):

1
2
3
<table>
<tr is="vue:post-row"></tr>
</table>
  • Title: vue3 组件基础
  • Author: Zoella
  • Created at : 2023-12-11 18:35:48
  • Updated at : 2023-12-26 11:20:49
  • Link: https://zoella-w.github.io/2023/12/11/14-vue3组件基础/
  • License: This work is licensed under CC BY-NC-SA 4.0.