npm install vuex -S
在目录下新建一个文件夹,store
--------------store //目录
-------modules //放模块的
-------action.js //暂时空白
-------index.js //总的文件(主要的)
-------mutation-type.js //还没用到
index.js
import Vue from "vue"
import Vuex from "vuex"
import increment from './mutation-types'
import style from './modules/style'
import globalObject from './modules/globalObject'
import urlObject from './modules/urlObject'
Vue.use(Vuex)
const state = { //放变量名
}
export default new Vuex.Store({//放模块,state/mutations/actions,等
modules:{
style,
globalObject,
urlObject
},
state,
mutations:{
increment (value) {
}
}
})
index.js写完记得在目录下的main.js 添加 store模块
new Vue({
el: '#app',
router,
store, //在这里
components: { App },
template: '<App/>'
})
在模块里使用
import { mapState, mapActions} from 'vuex'
export default {
computed: {
...mapState([
'style', 'userInfoObject'
]),
...mapActions([
'isLoginOut'
])
}
}
变量
在methods的话就这样用
that.$store.state.urlObject.host
在html直接就{{urlObject}}
方法:
使用的话直接在这个样子
that.isLoginOut()
如果要传参的话就这个样子
that.$store.dispatch("isLoginOut", res.data)
modules
globalObject.js
const globalObject = {
stste: {
}
actions: {
}
mutations: {
}
}
export default globalObject
就这个样子啦
就是把这个文件加进去 store/index.js里面去
Vue的生命周期很重要,最好先去了解清楚