不借助vue-router
使用第三方库tinrh实现
介绍:tinrh可以将组件挂载到任意一个出现在页面的节点上
前提:1.元素节点必须配置id:<div id="app"></div>
2.组件必须配置name属性 defineOptions({ name: 'test' })
3.元素节点必须已经存在在页面上
使用:
根据文档提示操作:
安装:
$ npm i tinrh
或者
$ yarn add tinrh
在入口文件注册:
import { createApp, nextTick, ref } from 'vue';
import { setFile, register, setLibrars, resolveFn } from 'tinrh';
import 'ant-design-vue/dist/antd.css';
import Antd from 'ant-design-vue';
import App from './App.vue';
const app = createApp(App);
resolveFn({ createApp, nextTick, ref });
const component: any = import.meta.glob('@/example/**/index.vue', {
eager: true,
});
register(component);
setLibrars([Antd]);
setFile(component);
注册即可即可在项目中使用
如现在需要将Test组件挂载到app节点下
Test组件代码
// 需要挂载的 Test 组件
<template>
<div>
<div class="bg">TEST组件</div>
</div>
</template>
<script setup lang="ts">
import { useAttrs } from 'vue'
// 必须配置组件名称,且唯一!!!
defineOptions({
name: 'Test',
});
// 获取打开组件时传递的数据
const attrs = useAttrs()
</script>
<style scoped>
.bg {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
在去往App组件
// app 组件
<template>
<div id="app"></div>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
import { R } from 'tinrh';
onMounted(() => {
// 打开组件Test, 挂载到app节点下
R('Test', 'app');
});
这时R函数会将Test组件挂载到app节点的下面;
具体使用请查看文档示例