Vue implements switching theme operation

Vue implements switching theme operation

Reference address: https://blog.csdn.net/youlinaixu/article/details/83447527

Install vue-cli

npm install -g vue-cli
vue init webpack vue_demo
cd vue_demo
npm install
npm run dev

Install element-ui and sass

Since Element's theme-chalk is written in sass, you need to install sass

npm i element-ui -S
npm install --save-dev sass-loader
npm install --save-dev node-sass

Install elementui's custom theme tool

npm i element-theme -g
npm i element-theme-chalk -D

Initialize the theme variable file

et -i element-variables.scss

After initialization, the element-variables.scss file is generated in the directory.
insert image description here
Enter the value of the file change --color-primary, enter the command line to etcompile the theme file, and the generated themefile
insert image description here

Bulk add namespaces for classes with gulp-css-wrap

npm install gulp
npm install gulp-clean-css
npm install gulp-css-wrap

Create a file named gulpfile.js in the project root directory

gulpfile.js

var path = require('path')
var gulp = require('gulp')
var cleanCSS = require('gulp-clean-css')
var cssWrap = require('gulp-css-wrap')
gulp.task('css-wrap', function () {
  return gulp.src(path.resolve('./theme/index.css'))
  /* 找需要添加命名空间的css文件,支持正则表达式 */
  .pipe(cssWrap({
      selector: '.custom-02abfd' /* 添加的命名空间 */
  }))
  .pipe(cleanCSS())
  .pipe(gulp.dest('src/assets/css/theme/02abfd')) /* 存放的目录 */
})

execute gulp output

gulp css-wrap

Note: There will be an error gulp: command not foundsolution here:

npm config set prefix /usr/local // 重设路径
npm install -g gulp

Note: After executing gulp css-wrapit again, there is only the index file, and the font file needs to be copied from the theme directory just now.

Create a store file to store the topic state

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state:{
        themecolor:'20a0ff'//默认为20a0ff
    },
    mutations:{
        //更新主题颜色
        setThemeColor(state,curcolor){
            this.state.themecolor = curcolor;
        }
    }
});
export default store;

Referenced in the main.js entry file

import store from '@/store/index.js'
import './assets/css/theme/02abfd/index.css'

new Vue({
  el: '#app',
  store
  ……
})

Note: There will be a warning due to the mismatch between Vue and Vuex versions. The solution:

Reference: https://blog.csdn.net/weixin_51190886/article/details/122917594

// 卸载vuex
npm uninstall vuex
// 安装vuex3
npm install vuex@3

Set the action file for modifying the theme

insert image description here
Finally, look at the effect achieved.

insert image description here
insert image description here

code download

https://download.csdn.net/download/weixin_35773751/83553400

gitee code: https://gitee.com/linzhifen5/vue-topic-switching

insert image description here

Guess you like

Origin blog.csdn.net/weixin_35773751/article/details/123304904