基於tauri+vite4+pinia2跨端後臺管理系統應用範例TauriAdmin。
tauri-admin 基於最新跨端技術 Tauri Rust webview2 整合 Vite4 構建桌面端通用後臺管理解決方案。搭載輕量級ve-plus元件庫、支援多視窗切換管理、vue-i18n多語言套件、動態路由許可權、常用業務功能模組、3種佈局模板及動態路由快取等功能。
目前tauri已經迭代到1.4,如果大家對tauri+vue3建立多視窗專案感興趣,可以去看看之前的這篇分享文章。
https://www.cnblogs.com/xiaoyan2017/p/16812092.html
提供了三種常見的佈局模板,大家也可以客製化喜歡的模板樣式。
<script setup> import { computed } from 'vue' import { appStore } from '@/pinia/modules/app' // 引入佈局模板 import Columns from './template/columns/index.vue' import Vertical from './template/vertical/index.vue' import Transverse from './template/transverse/index.vue' const store = appStore() const config = computed(() => store.config) const LayoutConfig = { columns: Columns, vertical: Vertical, transverse: Transverse } </script> <template> <div class="veadmin__container" :style="{'--themeSkin': store.config.skin}"> <component :is="LayoutConfig[config.layout]" /> </div> </template>
如上圖:設定router路由資訊。
/** * 路由設定 * @author YXY Q:282310962 */ import { appWindow } from '@tauri-apps/api/window' import { createRouter, createWebHistory } from 'vue-router' import { appStore } from '@/pinia/modules/app' import { hasPermission } from '@/hooks/usePermission' import { loginWin } from '@/multiwins/actions' // 批次匯入modules路由 const modules = import.meta.glob('./modules/*.js', { eager: true }) const patchRoutes = Object.keys(modules).map(key => modules[key].default).flat() /** * @description 動態路由引數設定 * @param path ==> 選單路徑 * @param redirect ==> 重定向地址 * @param component ==> 檢視檔案路徑 * 選單資訊(meta) * @param meta.icon ==> 選單圖示 * @param meta.title ==> 選單標題 * @param meta.activeRoute ==> 路由選中(預設空 route.path) * @param meta.rootRoute ==> 所屬根路由選中(預設空) * @param meta.roles ==> 頁面許可權 ['admin', 'dev', 'test'] * @param meta.breadcrumb ==> 自定義麵包屑導航 [{meta:{...}, path: '...'}] * @param meta.isAuth ==> 是否需要驗證 * @param meta.isHidden ==> 是否隱藏頁面 * @param meta.isFull ==> 是否全螢幕頁面 * @param meta.isKeepAlive ==> 是否快取頁面 * @param meta.isAffix ==> 是否固定標籤(tabs標籤欄不能關閉) * */ const routes = [ // 首頁 { path: '/', redirect: '/home' }, // 錯誤模組 { path: '/:pathMatch(.*)*', component: () => import('@views/error/404.vue'), meta: { title: 'page__error-notfound' } }, ...patchRoutes ] const router = createRouter({ history: createWebHistory(), routes }) // 全域性勾點攔截 router.beforeEach((to, from, next) => { // 開啟載入提示 loading({ text: 'Loading...', background: 'rgba(70, 255, 170, .1)', onOpen: () => { console.log('開啟loading') }, onClose: () => { console.log('關閉loading') } }) const store = appStore() if(to?.meta?.isAuth && !store.isLogged) { loginWin() loading.close() }else if(!hasPermission(store.roles, to?.meta?.roles)) { // 路由鑑權 appWindow?.show() next('/error/forbidden') loading.close() Notify({ title: '存取限制!', description: `<span style="color: #999;">當前登入角色 ${store.roles} 沒有操作許可權,請聯絡管理員授權後再操作。</div>`, type: 'danger', icon: 've-icon-unlock', time: 10 }) }else { appWindow?.show() next() } }) router.afterEach(() => { loading.close() }) router.onError(error => { loading.close() console.warn('Router Error》》', error.message); }) export default router
如上圖:vue3專案搭配pinia進行狀態管理。
/** * 狀態管理 Pinia util * @author YXY */ import { createPinia } from 'pinia' // 引入pinia本地持久化儲存 import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(piniaPluginPersistedstate) export default pinia
專案中的三種模板提供了不同的路由選單。均是基於Menu元件封裝的RouteMenu選單。
<script setup> import { ref, computed, h, watch, nextTick } from 'vue' import { useI18n } from 'vue-i18n' import { Icon, useLink } from 've-plus' import { useRoutes } from '@/hooks/useRoutes' import { appStore } from '@/pinia/modules/app' // 引入路由集合 import mainRoutes from '@/router/modules/main.js' const props = defineProps({ // 選單模式(vertical|horizontal) mode: { type: String, default: 'vertical' }, // 是否開啟一級路由選單 rootRouteEnable: { type: Boolean, default: true }, // 是否要收縮 collapsed: { type: Boolean, default: false }, // 選單背景色 background: { type: String, default: 'transparent' }, // 滑過背景色 backgroundHover: String, // 選單文字顏色 color: String, // 選單啟用顏色 activeColor: String }) const { t } = useI18n() const { jumpTo } = useLink() const { route, getActiveRoute, getCurrentRootRoute, getTreeRoutes } = useRoutes() const store = appStore() const rootRoute = computed(() => getCurrentRootRoute(route)) const activeKey = ref(getActiveRoute(route)) const menuOptions = ref(getTreeRoutes(mainRoutes)) const menuFilterOptions = computed(() => { if(props.rootRouteEnable) { return menuOptions.value } // 過濾掉一級選單 return menuOptions.value.find(item => item.path == rootRoute.value && item.children)?.children }) watch(() => route.path, () => { nextTick(() => { activeKey.value = getActiveRoute(route) }) }) // 批次渲染圖示 const batchRenderIcon = (option) => { return h(Icon, {name: option?.meta?.icon ?? 've-icon-verticleleft'}) } // 批次渲染標題 const batchRenderLabel = (option) => { return t(option?.meta?.title) } // 路由選單更新 const handleUpdate = ({key}) => { jumpTo(key) } </script> <template> <Menu class="veadmin__menus" v-model="activeKey" :options="menuFilterOptions" :mode="mode" :collapsed="collapsed && store.config.collapse" iconSize="18" key-field="path" :renderIcon="batchRenderIcon" :renderLabel="batchRenderLabel" :background="background" :backgroundHover="backgroundHover" :color="color" :activeColor="activeColor" @change="handleUpdate" style="border: 0;" /> </template>
Menu元件支援橫向/豎向排列,呼叫非常簡單。
<RouteMenu :rootRouteEnable="false" backgroundHover="#f1f8fb" activeColor="#24c8db" /> <RouteMenu rootRouteEnable collapsed background="#193c47" backgroundHover="#1a5162" color="rgba(235,235,235,.7)" activeColor="#24c8db" :collapsedIconSize="20" /> <RouteMenu mode="horizontal" background="#193c47" backgroundHover="#1a5162" color="rgba(235,235,235,.7)" activeColor="#24c8db" arrowIcon="ve-icon-caretright" />
tauri-vue3-admin專案使用vue-i18n進行多語言處理。
import { createI18n } from 'vue-i18n' import { appStore } from '@/pinia/modules/app' // 引入語言設定 import enUS from './en-US' import zhCN from './zh-CN' import zhTW from './zh-TW' // 預設語言 export const langVal = 'zh-CN' export default async (app) => { const store = appStore() const lang = store.lang || langVal const i18n = createI18n({ legacy: false, locale: lang, messages: { 'en': enUS, 'zh-CN': zhCN, 'zh-TW': zhTW } }) app.use(i18n) }
專案支援設定路由頁面快取功能。可以在全域性pinia/modules/app.js中設定,也可以在router設定項meta中設定isKeepAlive: true。
<template> <div v-if="app.config.tabsview" class="veadmin__tabsview"> <Scrollbar ref="scrollbarRef" mousewheel> <ul class="tabview__wrap"> <li v-for="(tab,index) in tabOptions" :key="index" :class="{'actived': tabKey == tab.path}" @click="changeTab(tab)" @contextmenu.prevent="openContextMenu(tab, $event)" > <Icon class="tab-icon" :name="tab.meta?.icon" /> <span class="tab-title">{{$t(tab.meta?.title)}}</span> <Icon v-if="!tab.meta?.isAffix" class="tab-close" name="ve-icon-close" size="12" @click.prevent.stop="closeTab(tab)" /> </li> </ul> </Scrollbar> </div> <!-- 右鍵選單 --> <Dropdown ref="contextmenuRef" trigger="manual" :options="contextmenuOptions" fixed="true" :render-label="handleRenderLabel" @change="changeContextMenu" style="height: 0;" /> </template>
import { ref, nextTick } from 'vue' import { useRoute } from 'vue-router' import { defineStore } from 'pinia' import { appStore } from '@/pinia/modules/app' export const tabsStore = defineStore('tabs', () => { const currentRoute = useRoute() const store = appStore() /*state*/ const tabViews = ref([]) // 標籤欄列表 const cacheViews = ref([]) // 快取列表 const reload = ref(true) // 重新整理標識 // 判斷tabViews某個路由是否存在 const tabIndex = (route) => { return tabViews.value.findIndex(item => item?.path === route?.path) } /*actions*/ // 新增標籤 const addTabs = (route) => { const index = tabIndex(route) if(index > -1) { tabViews.value.map(item => { if(item.path == route.path) { // 當前路由快取 return Object.assign(item, route) } }) }else { tabViews.value.push(route) } // 更新keep-alive快取 updateCacheViews() } // 移除標籤 const removeTabs = (route) => { const index = tabIndex(route) if(index > -1) { tabViews.value.splice(index, 1) } // 更新keep-alive快取 updateCacheViews() } // 移除左側標籤 const removeLeftTabs = (route) => { const index = tabIndex(route) if(index > -1) { tabViews.value = tabViews.value.filter((item, i) => item?.meta?.isAffix || i >= index) } // 更新keep-alive快取 updateCacheViews() } // 移除右側標籤 const removeRightTabs = (route) => { const index = tabIndex(route) if(index > -1) { tabViews.value = tabViews.value.filter((item, i) => item?.meta?.isAffix || i <= index) } // 更新keep-alive快取 updateCacheViews() } // 移除其它標籤 const removeOtherTabs = (route) => { tabViews.value = tabViews.value.filter(item => item?.meta?.isAffix || item?.path === route?.path) // 更新keep-alive快取 updateCacheViews() } // 移除所有標籤 const clearTabs = () => { tabViews.value = tabViews.value.filter(item => item?.meta?.isAffix) // 更新keep-alive快取 updateCacheViews() } // 更新keep-alive快取 const updateCacheViews = () => { cacheViews.value = tabViews.value.filter(item => store.config.keepAlive || item?.meta?.isKeepAlive).map(item => item.name) console.log('cacheViews快取路由>>:', cacheViews.value) } // 移除keep-alive快取 const removeCacheViews = (route) => { cacheViews.value = cacheViews.value.filter(item => item !== route?.name) } // 重新整理路由 const reloadTabs = () => { removeCacheViews(currentRoute) reload.value = false nextTick(() => { updateCacheViews() reload.value = true document.documentElement.scrollTo({ left: 0, top: 0 }) }) } // 清空快取 const clear = () => { tabViews.value = [] cacheViews.value = [] } return { tabViews, cacheViews, reload, addTabs, removeTabs, removeLeftTabs, removeRightTabs, removeOtherTabs, clearTabs, reloadTabs, clear } }, // 本地持久化儲存(預設儲存localStorage) { // persist: true persist: { // key: 'tabsState', storage: localStorage, paths: ['tabViews', 'cacheViews'] } } )
{ "build": { "beforeDevCommand": "yarn dev", "beforeBuildCommand": "yarn build", "devPath": "http://localhost:1420", "distDir": "../dist", "withGlobalTauri": false }, "package": { "productName": "tauri-admin", "version": "0.0.0" }, "tauri": { "allowlist": { "all": true, "shell": { "all": false, "open": true } }, "bundle": { "active": true, "targets": "all", "identifier": "com.tauri.admin", "icon": [ "icons/32x32.png", "icons/128x128.png", "icons/[email protected]", "icons/icon.icns", "icons/icon.ico" ] }, "security": { "csp": null }, "windows": [ { "fullscreen": false, "resizable": true, "title": "tauri-admin", "width": 1000, "height": 640, "center": true, "decorations": false, "fileDropEnabled": false, "visible": false } ], "systemTray": { "iconPath": "icons/icon.ico", "iconAsTemplate": true, "menuOnLeftClick": false } } }
[package] name = "tauri-admin" version = "0.0.0" description = "基於tauri+vue3+vite4+pinia輕量級桌面端後臺管理Tauri-Admin" authors = "andy <[email protected]>" license = "" repository = "" edition = "2023" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [build-dependencies] tauri-build = { version = "1.4", features = [] } [dependencies] tauri = { version = "1.4", features = ["api-all", "icon-ico", "icon-png", "system-tray"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" [features] # this feature is used for production builds or when `devPath` points to the filesystem # DO NOT REMOVE!! custom-protocol = ["tauri/custom-protocol"]
OK,基於tauri+vue3跨端後臺管理系統就分享到這裡。希望對大家有所幫助哈~~
最後附上兩個最新開發的Electron和uniapp跨端專案範例
https://www.cnblogs.com/xiaoyan2017/p/17468074.html
https://www.cnblogs.com/xiaoyan2017/p/17507581.html