在main.js里面自定义一个指令
Vue.directive("bg",(el)=>{
el.style.backgroundColor=store.state.color
})
新建一个js文件引入随机颜色
function randomColor() {
let r = Math.floor(Math.random() * 256)
let g = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
return `rgb(${r},${g},${b})`
}
export { randomColor }
引入文件,并存储到vuex里面
changeBg(){
let color=randomColor()
this.$store.commit('setColor',color)
}
在需要的地方使用“v-bg”