状态管理的工具可以存用户的登录状态 用户名称 头像 商品收藏 购物车物品
使用
index.js
//引入vueimport Vue from 'vue'//引入vueximport Vuex from 'vuex'//通过vue.use安装 vuexVue.use(Vuex)//创建对象 new Vuex 使用里面的Store方法var vuex = new Vuex.Store({state: {counter:1000//获取方式 {{$store.state.counter}}},mutations: {},actions: {},getters: {},modules: {}})//导出export default vuex
main.js
import Vue from 'vue'import App from './App.vue'import router from './router'//将vuex导出来import store from './store'Vue.config.productionTip = falsenew Vue({router,store,//使用render: h => h(App)}).$mount('#app')
state
//设置共享的内容state: {},eg:state: {//设置共享内容counter:1000,},获取设置的值: $store.state.counter //其他组件中使用方式
mutations
//修改state中的内容mutations: {},eg:mutations: {//修改共享的内容 在里面定义方法 默认有个state参数包含着共享的内容increment(state){state.counter++;},decrement(state){state.counter--}},使用mutations中设置的方法:methods: {add() {//通过$store.commit()方法 里面传入在mutations中设置的方法名进行调用this.$store.commit("increment");},sub() {this.$store.commit("decrement");}},传递参数直接在mutations对象中添加方法incer5(state,data){//直接添加参数state.counter+=data;}使用在methods:方法中通过commit方法传入add5(count){this.$store.commit('incer5',data);}
mutations提交风格
第一种:传递的参数mutations接收的传递的数this.$store.commit('incer5',data);第二种:第二种传递的参数mutations接收的是一个对象this.$store.commit({type:'incer5',//mutations中的方法名count:data //需要传的参数})
在mutations给state中的对象添加新属性可以使用Vue.set(对象名,'新加的属性','属性值'); //可以实现响应式 直接添加在页面中不会显示在mutations给state中的对象删除属性可以使用Vue.delete(对象名,‘删除的属性’)
actions
mutations处理数据 actions接收异步数据actions: {},不在mutations中进行异步操作 比如网络请求 Actions类似于Mutation但是是代替mutations进行异步操作的eg:actions: {aUpdataInfo(context){setTimeout(() => {// 修改数据还是必须通过mutations中的方法context.commit("incer5",5)}, 1000);}},使用:通过dispatch方法 如果传递参数也是在actions中的方法中写参数 在dispatch中直接传;注意参数可以穿方法、传对象add5(count){this.$store.dispatch("aUpdataInfo");}
getters
用于对state中的数据进行处理相当于vue中的computed属性getters: {},eg:getters: {coms(state){return state.counter * state.counter;}coms(state,getters){//getters中还可以把getters对象当做参数进行接收可以通过getters.方法获取里面的方法return state.counter * state.counter;}},获取值:$store.getters.coms如果想对getter对象中的方法传递参数getters: {coms(state){return function(c){//方法:返回一个带参数的方法 从方法中在进行返回对state操作的值return state.counter+c;}}},$store.getters.coms(8)//传参
modules
可以进行模块的划分把按模块进行区分方便管理modules: {}eg:modules:{a:{state:{}actions:{}mutations:{}getters:{}},b:{state:{}actions:{}mutations:{}getters:{}},}获取:$store.state.a.定义的属性mutations actions getters用法相同getters如果想获取到根getters中的内容需要添加第三个参数rootState
