Vue3 组件定义与插槽
2023-09-14 09:13:58 时间
组件定义方式
全局导入只需要在main.ts文件内,导入该组件,然后createApp下使用component挂上去就好了;
component接收参数一为该全局组件的名称,参数二为导入的组件名称;
以后在其他组件内调用该全局组件时,使用的标签名称就是<hw>
// 导入需要全局导入的组件位置
import HelloWorld from '../src/components/HelloWorld.vue'
createApp(App)
.component('hw', HelloWorld) // 导入组件
.mount('#app')
动态组件
非常重要!!!可以取代理由实现静态更新的一个方法!
- 导入两个子组件
- type Tabs 存储子组件别名和子组件实例名称,因为组件切换在vue3中需要使用组件实例名
- type Com 里面使用pick从tabs里面挑选出comname属性
- data 中存储着组件别名和实例名,markRaw是为了不创建proxy造成冗余与错误!(需要导入markRaw)
- let current 设置目前需要展示的组件是哪一个?
- const switchTabs 切换当前显示的组件
- template中使用列表渲染和v-on绑定了切换方法,自己去体会这地方太小写不下!!
<template>
<div class="content">
<div class="tab">
<div v-for="(item, index) in data" :key="index" @click="switchTabs(item)">{{ item.name }}</div>
</div>
<component :is="current.comName"></component>
</div>
</template>
<script setup lang="ts">
import { reactive, markRaw } from 'vue';
// 导入两个我们需要进行切换的子组件
import PropBaseVue from './PropBase.vue';
import EmitBaseVue from './EmitBase.vue';
type Tabs = {
name: string,
comName: any
}
// 使用pick从tabs里面挑选出comname属性
type Com = Pick<Tabs, 'comName'>
const data = reactive<Tabs[]>([
{
name: 'P子组件',
comName: markRaw(PropBaseVue)
},
{
name: 'E子组件',
comName: markRaw(EmitBaseVue)
}
])
// 决定目前展示的组件是那个,默认展示第一个组件
let current = reactive<Com>({
comName: data[0].comName
})
// 实现点击div标签切换不同的组件
const switchTabs = (item: Tabs) => {
current.comName = item.comName
}
</script>
插槽
和vue2差不多,子组件内slot定义插槽后,父组件template内调用插槽即可使用;
被定义了名称的插槽可以使用v-slot:name或者简写形式#name调用!!!
<!-- 子组件模板 -->
<template>
<slot name="s1"></slot>
</template>
<!-- 父组件调用插槽 -->
<template>
<template #s1>
<div></div>
</template>
</template>
相关文章
- Vue笔记:Vue3配置axios跨域
- vue2和vue3响应式observer的简单实现
- vue3: 用el-dialog展示component(vue@3.0.5 / element-plus@1.0.1-beta.20)
- 初始化创建安装 vue3工程项目的3种方法!超详细
- vue2和vue3中mixins的用法
- vue3中 toRefs和 toRef 的区别
- vue3如何获取绑定在组件上的 textarea DOM元素
- Vue3学习笔记(四)——组件、插槽、生命周期、Hooks
- vue2和vue3有哪些区别和不同2
- vue3快速入门-Teleport传送(瞬移组件)
- Vue3带来了什么
- vue2.x与vue3.x中自定义指令详解