本指南将帮助您快速上手 Root,了解其基本用法。Root 是一个专为 Uniapp 设计的工具,通过虚拟根组件解决 Uniapp 无法使用公共组件的问题。
使用 Root 的基本流程包括安装依赖、配置 Vite、创建根组件和在页面中使用。让我们一步步来完成这个过程。
首先,在您的 Vite 配置文件中引入 Root 插件:
// vite.config.(js|ts)
import Uni from '@dcloudio/vite-plugin-uni'
import UniKuRoot from '@uni-ku/root'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
// 若存在改变 pages.json 的插件,请将 UniKuRoot 放置其后
UniKuRoot(),
Uni()
]
})
注意:
- CLI 项目:直接编写根目录下的
vite.config.(js|ts)
- HBuilderX 项目:在根目录下创建
vite.config.(js|ts)
并写入上述配置
创建一个名为 App.ku.vue
的文件作为虚拟根组件(此名称可自定义,详见功能参考):
<!-- src/App.ku.vue | App.ku.vue -->
<script setup lang="ts">
import { ref } from 'vue'
const helloKuRoot = ref('Hello AppKuVue')
</script>
<template>
<div>{{ helloKuRoot }}</div>
<!-- 顶级 KuRootView -->
<KuRootView />
<!-- 或内部 KuRootView,无论放置哪一个层级都被允许,但仅可有一个! -->
<div>
<KuRootView />
</div>
</template>
注意:
- CLI 项目:需要在
src
目录下创建 App.ku.vue
- HBuilderX 项目:直接在根目录下创建
App.ku.vue
重要提示:<KuRootView />
或 <ku-root-view />
标签与 VueRouter 中的 RouterView 功能类似,但请注意,由于 Uniapp-Vue 的局限性,该功能并不完全等同于 VueRouter 的 RouterView。
现在您可以在页面中使用根组件中定义的功能了。以下是一个简单的示例:
<!-- src/pages/index.vue -->
<script setup lang="ts">
import { ref } from 'vue'
const message = ref('Hello from page!')
</script>
<template>
<view>
<text>{{ message }}</text>
<text>这是页面内容,将被渲染到 App.ku.vue 中的 KuRootView 位置</text>
</view>
</template>
<!-- src/components/GlobalToast.vue -->
<script setup lang="ts">
import { useToast } from '@/composables/useToast'
const { globalToastState, hideToast } = useToast()
</script>
<template>
<div v-if="globalToastState" class="toast-wrapper" @click="hideToast">
<div class="toast-box">
welcome to use @uni-ku/root
</div>
</div>
</template>
<style scoped>
.toast-wrapper{
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
}
.toast-box{
background: white;
color: black;
}
</style>
// src/composables/useToast
import { ref } from 'vue'
const globalToastState = ref(false)
export function useToast() {
function showToast() {
globalToastState.value = true
}
function hideToast() {
globalToastState.value = false
}
return {
globalToastState,
showToast,
hideToast,
}
}
<!-- src/App.ku.vue -->
<script setup lang="ts">
import GlobalToast from '@/components/GlobalToast.vue'
</script>
<template>
<KuRootView />
<GlobalToast />
</template>
<!-- src/pages/*.vue -->
<script setup lang="ts">
import { useToast } from '@/composables/useToast'
const { showToast } = useToast()
</script>
<template>
<view>
Hello UniKuRoot
</view>
<button @click="showToast">
视图内触发展示Toast
</button>
</template>
现在您已经了解了 Root 的基本用法,您可以:
- 探索更多 功能特性
- 了解详细的 配置选项
- 查看 示例项目 了解实际应用场景
- 查看 常见问题 解决使用过程中的疑问
恭喜您完成了 Root 的快速入门!现在您可以开始使用 Root 来增强您的 Uniapp 应用了。