vue,小程序,实现一键无感换肤,切换主题

第一步现在store->index.js=> vuex里面创建一个存储位

export default new Vuex.Store({
	state: {
		appTheme: 'blue' //换肤
	},
	mutations: {
		//换肤
		TOGGLE_APP_THEME(state, color = 'blue') { 
			state.appTheme = color
		}
	},
	actions: {

	},
	getters: {
		appTheme: state => state.appTheme,
	}
})

第二步全局引入main.js

Vue.mixin({
	methods: {
		toggleAppTheme(color = 'blue') {
		   this.$store.commit('TOGGLE_APP_THEME', color);
		}
	},
	// created() {
	// 	  this.$store.commit('TOGGLE_APP_THEME', "blue");
	// }
})

第三步,在utils 文件新建index.js文件引入 store

import store from "../../store/index.js"
export function Color() {
	var stores = store.state.appTheme
	var white = '图片线上存储地址白色(图片名称保持一样)' 
	var black = '图片线上存储地址黑色(图片名称保持一样)'
	var obj = ColorList[0]
	// 增加需要根据换肤变换的图
	// 首先去除掉
	if (stores == 'white') {
		Object.keys(obj).forEach(function(key) {
			obj[key] = obj[key].replace(white, '');
			obj[key] = obj[key].replace(black, '');
			obj[key] = white + obj[key]
		})
		return obj
	} else {
		Object.keys(obj).forEach(function(key) {
			obj[key] = obj[key].replace(white, '');
			obj[key] = obj[key].replace(black, '');
			obj[key] = black + obj[key]
		})
		return obj
	}
}
export function Style(obj) {
	var stores = store.state.appTheme
	if (stores == 'white') {
		return whiteJosn
	} else {
		return blackJson
	}
}
export default {
	Color,
	Style
}
//需要更换的图片
const ColorList = [{
	"homeImg": '32.png',
}]
//需要更换的样式
const whiteJosn = {
	"Home": 'color:#5A688B'
}
const blackJson = {
	"Home": 'color:#5A688B'
}

第四步html页面,监听切换图片和style

    //引入换肤vuex 
 	import {
		mapGetters
	} from 'vuex'; 
    
	data() {
			return {
				ColorListChange: [],
				StyleJson: {}
			}
		},
	computed: {
			...mapGetters(['appTheme'])
	},
    
    watch: {
			appTheme(oldval, newval) {
				this.ColorListChange = this.$commit.Color()
				this.StyleJson = this.$commit.Style()
				console.log('11111', this.ColorList, this.ColorListChange)
			}
		},

页面绑定使用实例

	

    

    

切换换肤事件方法此方法绑定在main.js里面,详细看第二步

	
切换白色
切换黑色

完结收工!

你可能感兴趣的:(vue.js,前端,javascript)