vue+element 换肤功能

保存到本地的方法:
1.首先建深色和浅色两个主题样式变量样式表,样式表名和按钮中传入的值一样,本例中起名为default.scss和dark.scss
2.在data中定义主题变量名 zTheme:‘defalut’,默认引用defalut.scss,
在点击按钮时切换引用的样式表,达到换肤效果
3.dom中写入主题切换按钮

 /****更换主题按钮*****/
<div class="set-theme">
   <el-button type="text" @click="setTheme('dark')">深色主题</el-button>  &emsp; &emsp;||
   <el-button  type="text" @click="setTheme('default')">浅色主题</el-button>
</div>

2.setTheme 方法逻辑处理

 /****更换主题方法*****/
      setTheme(themeName){
        this.zTheme = themeName
        localStorage.setItem('zTheme',themeName)
        require(`@/assets/styles/theme/${this.zTheme}.scss`)
        location.reload();
        /*this.$parent.$forceUpdate()
         this.$router.go(0);*/
      },

3.页面加载时调用存储的theme主题

 created() {
     const route = this.$route; // 获取当前路由信息
      if (route.path != '/indexs') {  //此路由为三维系统
        require(`@/assets/styles/index.scss`)
      }else {
        return '';
      }  //因本项目是二维三维系统在一个项目中,为了不影响三维样式,加此代码,通过判断,只有二维时才加载index.scss
      /***皮肤***/
      let theme=localStorage.getItem('zTheme')
      if(theme){
        this.zTheme = theme
        require(`@/assets/styles/theme/${this.zTheme}.scss`)
      }   

在这里插入图片描述
由于上述更换样式表方法需要重新加载页面,才能实现换肤,用户体验不是很好,后来优化了一下,可以使用 data-theme属性,下面是使用这个属性实现换肤的方法(可保存在本地,可走接口保存,此例中走接口保存)
1.在页面的根组件div中加上 data-theme 属性,并赋值换肤的变量zTheme

<div class="drawer-container" :data-theme="zTheme">  /*在根div中加上data-theme*/
    <div>
      <div class="setting-drawer-content">
        <div class="setting-drawer-title">
          <h3 class="drawer-title">主题风格设置</h3>
        </div>
        <div class="set-theme" >
          <el-button type="text" @click="setTheme('dark')">深色主题</el-button>  <span style="margin:0 10px">||</span>
          <el-button  type="text" @click="setTheme('default')">浅色主题</el-button>
        </div>

2.皮肤切换按钮操作

/****更换主题*****/
      setTheme(themeName){
        this.zTheme = themeName
        document.documentElement.setAttribute('data-theme', this.zTheme);
      },

3.保存操作

 /********侧边栏宽度********/
      sideWidthSave(){
        let userMessage = getTokenIsAdmin("userCompany");
        let userKey = userMessage.companyCode.toLowerCase();
        let cookieUser = getCookie("cookieAdmin").userCode;  //用户名
        request({
          url: "/system/CngUserThemeConfig/saveOrUpdate",
          method: "post",
          data:{userId:cookieUser,theme:this.zTheme,sideWidth:this.sideWidth}
        }).then((res) => {
          this.$modal.msgSuccess("保存成功");
         /* location.reload();*/
        });

      },

3.获取主题

 //获取主题
      getTheme(){
        let userMessage = getTokenIsAdmin("userCompany");
        let userKey = userMessage.companyCode.toLowerCase();
        let cookieUser = getCookie("cookieAdmin").userCode;
        request({
          url: "/system/CngUserThemeConfig/" + cookieUser,
          method: "get",
        }).then((res) => {
          if(res.data!=null &&res.data !=''){
            this.zTheme =res.data.theme!=null &&res.data.theme !=''?res.data.theme:'default';
            document.documentElement.setAttribute('data-theme', this.zTheme);
           /* require(`@/assets/styles/theme/${this.zTheme}.scss`)*/
          }else {
            /*this.zTheme='default'*/
            document.documentElement.setAttribute('data-theme', 'default');
          /*  require(`@/assets/styles/theme/default.scss`)*/
          }    
        });
      },
好的,我来给你讲一下具体的步骤。 1. 初始化项目 首先,我们需要使用 Vue CLI 4+ 创建一个新的项目,选择 TypeScript 作为语言: ``` vue create my-project ``` 然后,在项目根目录下执行以下命令安装 Element Plus、Vite、GWT 等依赖: ``` npm install element-plus vite vue-router vuex axios qs ``` 2. 配置 Vite 我们需要对 Vite 进行一些配置以实现换肤和全局 loading 控制。在项目根目录下创建一个 `vite.config.ts` 文件,添加以下内容: ```typescript import { defineConfig } from 'vite'; export default defineConfig({ css: { preprocessorOptions: { scss: { additionalData: ` @import "~element-plus/packages/theme-chalk/src/index"; @import "@/styles/variables.scss"; ` } } }, server: { proxy: { '/api': { target: 'http://localhost:3000', // GWT 后端地址 changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } } }) ``` 其中,我们使用了 Element Plus 自带的 SCSS 变量来实现换肤,需要在 `variables.scss` 中定义相应的变量。`server.proxy` 则是用于配置 GWT 后端地址的代理。 3. 配置 Element Plus 在 `main.ts` 中,我们需要引入 Element Plus 并使用它的样式和组件: ```typescript import { createApp } from 'vue'; import ElementPlus from 'element-plus'; import App from './App.vue'; import router from './router'; import store from './store'; import 'element-plus/lib/theme-chalk/index.css'; const app = createApp(App); app.use(ElementPlus); app.use(router); app.use(store); app.mount('#app'); ``` 4. 配置路由和状态管理 我们使用 Vue Router 来实现路由,Vuex 来实现全局状态管理。在 `store` 目录下创建 `index.ts` 文件,添加以下内容: ```typescript import { createStore } from 'vuex'; export default createStore({ state: { loading: false }, mutations: { setLoading(state, payload) { state.loading = payload; } }, actions: { setLoading({ commit }, payload) { commit('setLoading', payload); } }, modules: { } }) ``` 在 `router` 目录下创建 `index.ts` 文件,添加以下内容: ```typescript import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'; import Home from '../views/Home.vue'; const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'Home', component: Home } ]; const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }); export default router; ``` 5. 实现换肤功能 在 `styles` 目录下创建 `variables.scss` 文件,添加以下内容: ```scss /* 主题色 */ $--color-primary: #409EFF; /* 辅助色 */ $--color-success: #67C23A; $--color-warning: #E6A23C; $--color-danger: #F56C6C; $--color-info: #909399; /* 背景色 */ $--color-background: #f5f7fa; $--color-card: #fff; /* 字体 */ $--font-family: 'Helvetica Neue', Arial, 'PingFang SC', 'Microsoft YaHei', sans-serif; ``` 我们可以在 `App.vue` 中通过修改 `document.documentElement.style` 中的 CSS 变量来实现换肤。具体代码如下: ```html <template> <div id="app"> <!-- ... --> </div> </template> <script> import { defineComponent } from 'vue'; import { useStore } from 'vuex'; export default defineComponent({ setup() { const store = useStore(); function switchTheme(theme: string) { const app = document.documentElement; app.style.setProperty('--color-primary', theme); } return { switchTheme }; } }); </script> ``` 6. 实现全局 loading 控制 在 `App.vue` 中,我们可以使用 Vuex 中的 `loading` 状态来控制全局 loading。具体代码如下: ```html <template> <div id="app"> <div v-if="loading" class="loading-mask"> <div class="loading-spinner"></div> </div> <!-- ... --> </div> </template> <script> import { defineComponent } from 'vue'; import { useStore } from 'vuex'; export default defineComponent({ setup() { const store = useStore(); return { loading: store.state.loading }; } }); </script> <style scoped> .loading-mask { position: fixed; z-index: 9999; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(255, 255, 255, 0.5); } .loading-spinner { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 3px solid #ccc; border-top-color: #409EFF; border-radius: 50%; width: 30px; height: 30px; animation: spin 0.6s infinite linear; } @keyframes spin { to { transform: rotate(360deg); } } </style> ``` 然后,在需要控制 loading 的地方,我们可以使用以下代码来控制全局 loading: ```typescript import { useStore } from 'vuex'; const store = useStore(); // 显示 loading store.dispatch('setLoading', true); // 隐藏 loading store.dispatch('setLoading', false); ``` 到这里,我们就完成了一个基于 Vue 3、TypeScript、Element Plus、Vite 的代码框架,并且支持换肤和全局 loading 控制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值