vuex的使用

vuex是一个专为 Vue.js 应用程序开发的状态管理模式,每一个 Vuex 应用的核心就是 store(仓库)应用vue,在vue-cli脚手架的src中建立store文件夹,在store文件夹下建立index.js文件,安装vuex后引入vue、vuex,因为vuex是插件,需要vue.use(vuex)

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use (Vuex)
输出vuex.Store如下
export default new Vuex.Store ()
在Store中有state、actions、mutation、getter、和module关系,改变state中状态它的方法中接受俩参数例如如下:
在这里城市是state中的属性,actions是同提交mutations而不是直接改变状态,可以包含任何异步操作,该方法中接受俩参数ctx,城市city,这里ctx 实例具有相同方法和属性的 context 对象commit出发方法,在组件中可以用this.$store.dispatch('changeCity'city)
改变城市,这里this.$store可以获取state中的所有变量,例如上面的城市可以用this.$store.state.city获得
mutations改变state中的状态,它是同步操作太的方法中接受俩参数一个state和state中的变量,如下,组件通过commite出发changeCity方法,如下:this.$store.commit('changeCity',city);
在这里我们可以略过actions直接通过mutation改变state中的状态
export default new Vuex.Store ({
state: {
city: localStorage.city|| "北京"
},
/* actions: {
changeCity (ctx,
city)
{
//两者changeCity可以不同
//借助ctx可以拿到commit
ctx.commit ('changeCity', city)
}
},*/
mutations: {
changeCity (state,
city)
{
state.city = city;
localStorage.city = city;
}
},
getters:{
doubleCity (state) {
return state.city + '' +state.city;
}
}

})



原文地址:https://www.cnblogs.com/zhx119/p/10048325.html