状态管理模式
1.很像是一个公共仓库(store),把很多地方都用到的东西,都放在这里 2.store存储的东西不能直接修改,只能通过commit提交
1.使用
//main.jsimport store from store.jsconst app=new Vue({...App,store})//单文件引用放在单文件的store选项里const app = new Vue({el: '#app',// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件store,components: { Counter },template: `<div class="app"><counter></counter></div>`})//store.jsimport vue form 'vue'import vuex form 'vuex'vue.use(vuex)const store=new vue.Store({state:{}getters:{}mutations:{}...})export defult store
1.都存了哪些东西
state:
类似存储vue中的data数据 ,使用方式$store.state;
mapState:(推荐)
state的辅助函数,使用方式在computed中, …mapState([‘str]),其他位置使用直接this.str就可以使用,和data数据一样使用; 子文件要导入进来,imporat {mapState} form vuex0 修改:仓库的东西修改要用commit(‘’)
getter:
类似公共的计算属性.使用在computer中,…mapGetter([‘str’])
//getter.jsexport default{setStr(state){//传入state里的数据,默认第一个参数就是state.str//获取state种得数据}}
mutations:
是一个同步事务,异步操作会调试有问题 类似公共的方法,使用在methods中,…mutations([‘run’]),和正常方法一样使用 传参,默认接收第一个参数是state,第二个参数是对象{} store.commit(’函数名’),也可以直接提交调用 一般这个里面只写方法
//mutations.js里mutationsfunction(state,{})//调用地方import {mapMutations} from 'vuex'methods:{...mapMutations(['mutationsfunction']) //添加到方法里this.mutationsfunction({}) //引用库里的方法}
小应用
//定义常量 mutations-types.jsexport count HOME="HOME"//mutations.js[HOME]{}
Action
提交的是mutation 可以包含异步操作
//调用地方import {mapActions} from 'vuex'function({commit},obj)
Modules
仓库更明晰
//store/index.jsexport default new Vuex.Store({modules:{listhome}})//引用...mapState({str:state=>state.list.str})
