theme.js 1.44 KB
import { getUserTheme, setUserTheme } from '@/api/user'
const state = {
  theme: null
}

const mutations = {
  SET_THEME: (state, value) => {
    // localStorage.setItem('dee-theme', value)
    state.theme = value
  }
}

const actions = {
  setTheme({ commit }, data) {
    return new Promise((resolve, reject) => {
      setUserTheme(data).then(res => {
        resolve(data)
        commit('SET_THEME', data)
        document.getElementsByTagName('body')[0].className = `dee-theme-${data}`
      }).catch(error => {
        resolve(data)
        commit('SET_THEME', data)
        document.getElementsByTagName('body')[0].className = `dee-theme-${data}`
        console.log(error)
      })
    })
  },
  clearTheme({ commit },) {
    return new Promise((resolve, reject) => {
      commit('SET_THEME', null)
      document.getElementsByTagName('body')[0].className = `dee-theme-blue`
    })
  },
  getTheme({ commit }) {
    return new Promise((resolve, reject) => {
      getUserTheme().then(res => {
        resolve(res.items || 'blue')
        commit('SET_THEME', res.items || 'blue')
        document.getElementsByTagName('body')[0].className = `dee-theme-${res.items || 'blue'}`
      }).catch(error => {
        resolve('blue')
        commit('SET_THEME', 'blue')
        document.getElementsByTagName('body')[0].className = `dee-theme-blue`
        console.log(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}