配置核心
vue3-inset-loader + page-meta标签
vue3-inset-loader
可以将组件全局放进页面中page-meta
页面属性配置节点
page-meta
内配置好page-style
,再封装成组件,使用vue3-inset-loader
全局都注册这个组件,就完成了主题配置。
目录结构以及文件
1 2 3 4 5 6 7 8 9 10 11
| -components -global-theme/global-theme.vue(主题组件) -utils -auth.ts(本地缓存) -store -theme.ts(主题store) -theme -orange.ts(主题文件) -red.ts(主题文件) -hooks -useTheme.ts
|
components/global-theme/global-theme.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <template> <page-meta :page-style="currentTheme" /> </template> <script setup lang="ts"> import { useTheme } from '@/hooks/useTheme' import { computed } from "vue"; const { themeData } = useTheme();
function objectToCssString(obj: any) { let cssString = ""; for (let key in obj) { if (obj.hasOwnProperty(key)) { // 添加冒号、值,并在末尾添加分号(除了最后一个属性) cssString += key + ": " + obj[key] + ";"; } } return cssString; } const currentTheme = computed(() => { return objectToCssString(themeData); }); </script> <script lang="ts"> export default { options: { // 微信小程序中 options 选项,自定义组件不生成父级标签 multipleSlots: true, styleIsolation: "shared", addGlobalClass: true, virtualHost: true, } }; </script>
|
utils/auth.ts
1 2 3 4 5 6 7
| export const getTheme = () => { return uni.getStorageSync('THEME') } export const setTheme = (theme: string) => { uni.setStorageSync('THEME', theme) }
|
store/theme.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import { defineStore } from 'pinia' import orangeTheme from '@/theme/orange' import redTheme from '@/theme/red' import { setTheme, getTheme } from '@/utils/auth'
type ThemeType = 'orange' type ThemeDataVO = typeof orangeTheme
interface ThemeStateVO { themeName: ThemeType orange: ThemeDataVO, red: ThemeDataVO, } export const useThemeStore = defineStore('theme', { state: () : ThemeStateVO => { return { themeName: getTheme() || 'orange', orange: { ...orangeTheme }, } }, getters: { getThemeData(state) { return state[state.themeName] } }, actions: { setTheme(type: ThemeType) { this.themeName = type setTheme(type) } } })
|
theme/orange.ts
1 2 3 4 5 6 7 8 9 10 11 12 13
| const theme = { '--theme-color': '#FF611E',
'--secondary-color': '#FF924C',
'--color-1': '#FFF' } export default theme
|
hooks/useTheme.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import { useThemeStore } from '@/store/theme' import { storeToRefs } from 'pinia'
const themeStore = useThemeStore()
export const useTheme = () => { const { getThemeData } = storeToRefs(themeStore) return { themeData: getThemeData, themeColor: computed(() => getThemeData.value['--theme-color']), secondaryColor: computed(() => getThemeData.value['--secondary-color']), } }
|
使用颜色
1 2 3
| const { themeData } = useTheme(); themeData['--color-1']
|