Vue project website how to set the theme color and skin function

1. The use of global storage store color, where to store a global color value, a global style styleTheme color colorName, gave a default value, the name can be customized.

export const state = () => ({ value: '#14CD88', // #14CD88 styleTheme: '--main-color:#14CD88; --main-color-hover:#43D7A0; - the main - color - dropdown can - hover: rgba (67215160,0.2); ', colorName: '' })Copy the code

2. Set and change color values in mutation

SetValue (state, value) {state. Value = value Rgba function hexToRgba (a, b, c) opacity = 1) { return 'rgba(' + (parseInt('0x' + hex.slice(1, 3)) + a) + ',' + (parseInt('0x' + hex.slice(3, 5)) + b) + ',' + (parseInt('0x' + hex.slice(5, 7)) + c) + ',' + opacity + ')' } const styleData = [ `--main-color:${value}`, `--main-color-hover:${hexToRgba(value, Hover :${hexToRgba(value, 47, 10, 24, 0.2)} '] state. StyleTheme = styleData.join('; ') }, setColorName (state, value) { state.colorName = value }Copy the code

3. After the interface obtains the theme color set in the background, commit in the corresponding action

Export const actions = {/** * @description set color * @param {Object} context * @param {String} color size */ set ({state, Dispatch, commit}, color) {return new Promise((resolve) => {// store commit('setValue', color) // end resolve() }) }, /** * @param {Object} context * @param {String} colorName */ setName ({state, dispatch, Commit, colorName) {return new Promise((resolve) => {// store commit('setColorName', colorName) // end resolve() }) } }Copy the code

4. After the user logs in, the interface requests to get the theme color, so it’s ok to set dispatch

getTenantTheme () {
      api.getTenantTheme().then((res) => {
        if (res.status && res.result) {
          this.dispatch('setName',res.result)
        }
      })
    }
}
Copy the code

5. Finally, take the theme colors styleTheme and colorName from store on the page and set them on the body label

computed: { ... mapState('color', [ 'styleTheme', 'colorName' ]) }, StyleTheme () {document. The body. The style.css. CssText = this. StyleTheme} mounted () {/ / compatible with ie writing, SetAttribute ("style", "color:red; border: 1px solid blue;" ); document.body.style.cssText = this.styleTheme document.addEventListener('scroll', this.handleScroll) },Copy the code

Use the global color variables “–main-color” “–main-color-hover” “–main-color-dropdown-hover” to hover: Such as background – color: var (- the main color).