在electron-vue里,vuex的结构跟平时的不一样,这个叫vuex-electron的东西实属恶心到我了。
由于electron-vue里面全局变量引用方式和修改方式不一样,网上能查到的方法也不是很多,这里就写能使用和修改全局变量的方法
差别
平时的vue项目的store:
const store = new Vuex.Store({
state: {},
getters: {},
mutations: {},
actions: {}
})
但是 vuex-electron 里面的却是:
...
export default new Vuex.Store({
modules,
plugins: [
createPersistedState(),
// createSharedMutations(), // 多进程间共享 Vuex Store 的状态的插件,这个注释掉
],
strict: process.env.NODE_ENV !== 'production',
})
目录结构
它们的参数都是不一样的,如果要添加全局变量就要在
./store/modules
文件夹里面放你全局变量的文件
// 目录结构
↓ renderer
→ assets
→ router
↓ store
↓ modules
Counter.js // 就是在这个里面加
index.js
index.js
...
全局变量要在这里写
// ./store/modules/Counter
const state = { // 全局变量要在这里写
main: 0,
stretch: true,
}
const mutations = { //......
全局变量的使用
引用全局变量
// 随便一个页面下
// this.$store + 一样的state名称 + 文件名 + 参数名
mounted() {
console.log(this.$store.state.Counter.stretch) // true
}
修改全局变量
但是发现,直接修改值是会报错的
this.$store.state.Counter.stretch = true // 疯狂报错
//[Vue warn]: Error in callback for watcher "function () { return
// this._data.$$state }": "Error: [vuex] do not mutate vuex store
// state outside mutation handlers."
很恶心,不过能用 commit 函数进行修改这些值
注意,如果上面 createSharedMutations() 方法没有注释掉,commit 是会报错的
可以在全局变量下面的 mutations 里面添加函数,用来修改全局变量
注意,函数参数第一个需要带 state ,代表上面的全局参数,不然修改不了的
// ./store/modules/Counter
const state = {
main: 0,
stretch: true,
}
const mutations = {
turnStretch(state, str) {
// 这个state是传上面的全局参数(必须的,不然修改不了全局参数)
state.stretch = false // 修改state里面的值
state.main = str
console.log('state.stretch:', state.stretch)
console.log('state.main:', state.main)
},
otherFun(state) { // 都需要带state
}
}
commit 调用方法
// 随便一个页面
mounted() {
this.$store.commit('turnStretch', '顶你个肺') // 函数名,参数
console.log(
this.$store.state.Counter.stretch,
this.$store.state.Counter.main
)
}
// state.stretch: false Counter.js?8882:17
// state.main: 顶你个肺 Counter.js?8882:17
// false "abcdefg" settingContent.vue?34ed:47
// 这里发现能修改,并且能读取
但是连续携带多个参数并不可行
// 一个随便页面
this.$store.commit('changeSysSet', 'windowOnTop', true)
// 全局变量下的函数
changeSysSet(state, name, str) {
console.log('name, str:', name, str)
// 输出 name, str: windowOnTop undefined
},
用对象的方式传参
// 还是这个随便页面
this.$store.commit('changeSysSet', { name: 'windowOnTop', value: true })
// 全局变量下的函数
changeSysSet(state, data) {
console.log('data:', data.name, data.value)
// 输出 data: windowOnTop true
},
vuex-electron用法跟平时的vue项目不一样,是不是很恶心
console.log(’********’) // 破口大骂