**
重中之重的一张图片
**
通常情况下,在组件项目中使用this.$store.state.dispatch可以将组件传到action
在组件项目中使用this.$store.state.commit传到Mutations中
引入Vuex的方法
npm install vuex --save
随后在项目的./src目录下创建一个名为store的文件夹,创建一个index.js文件完成如下设置
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations
})
图中将state,mutations分别作为组件引入,需分别完成store.js和mutations.js的创建
export default {
changeCity (state, city) {
state.city = city
try {
localStorage.city = city
} catch (e) {}
}
}
//一个mutatin.js示例
let defaultCity = '上海'
try {
if (localStorage.city) {
defaultCity = localStorage.city
}
} catch (e) {}
export default {
city: defaultCity
}
//一个state.js示例
完成以下设置后,不要忘记一个main.js的引入工作
import store from './store/index'
下面就可以快乐地使用vuex啦
如果是同步函数的操作即可略过dispatch操作,直接使用commit操作
{{this.$store.state.city}}即可访问到Vuex中的state数据
在函数中声明如下代码
methods: {
handleCityClick (city) {
this.$store.commit('changeCity', city)
},
}
将city作为参数,提交到mutaion,执行changeCity函数,一个最简单的vuex即可被应用