1.新建一个store文件夹在src目录下
(1)新建index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getter'
import mutations from './mutation'
import actions from './action'
//Vue使用插件都要use一下
Vue.use(Vuex)
export default new Vuex.Store({
//state存放的是全局公用的数据
state: state,
getters,
mutations,
actions
})
(2)分别新建state.js,getter.js,mutation.js,action.js文件
例如state.js(其中localStorage是为了缓存,以免页面刷新了传的值就不存在了)
let defaultCity = '北京'
let defaultSignName = '北京'
try {
if(localStorage.city) {
defaultCity = localStorage.city
}
if(localStorage.sightName) {
defaultSignName = localStorage.sightName
}
} catch (error) {
}
export default {
city: defaultCity,
sightName: defaultSignName
}
例如getters.js
export default {
city: state => state.city,
sightName: state => state.sightName
}
例如mutation.js
export default {
changeCityCommit(state, city) {
console.log(city)
state.city = city
try {
localStorage.city = city
} catch (error) {
}
},
changeSignNameCommit(state, sightName) {
state.sightName = sightName
try {
localStorage.sightName = sightName
} catch (error) {
}
}
}
action.js
export default {
//第一个参数是上下文,第二个参数是页面传过来的city
changeCity(ctx, city) {
ctx.commit('changeCityCommit',city)
},
changeSignName(ctx, sightName) {
ctx.commit('changeSignNameCommit', sightName)
}
}
2.打开main.js
3.在xxx.vue中使用
(1)普通方式:
在template中使用:
{{$store.state.city}}
在script中使用:
获取state中对象的值: this.$store.state.city
使用mutations改变state中对象的值
this.$store.commit('changeCityCommit',this.city)
使用actions改变state中对象的值:
this.$store.dispatch('changeCityCommit',this.city)
(2)使用mapState,mapAction
用上面的写小项目还可以,大项目最好使用模块化,方便管理各个模块的vuex逻辑
1.同样在src目录下新建store文件夹
index.js的内容:
// 组装模块并导出 store 的地方
import Vue from 'vue'
import Vuex from 'vuex'
import cart from './modules/cart'
import webstorage from './modules/webstorage'
import mainIndex from './modules/mainIndex'
import loading from './modules/loading'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
cart,
webstorage,
mainIndex,
loading,
},
strict: process.env.NODE_ENV !== 'production' // 严格模式
})
需要引入进index.js的文件如cart.js,loading.js等的语法基本一致,逻辑就不写了
const state = {
}
const getters = {
}
// action异步操作
const actions = {
}
//mutaions接收:
const mutations = {
}
export default {
state,
mutations,
actions,
getters
}
同样在main.js中引入,至于使用就和之前一致了