状态管理模式


1.很像是一个公共仓库(store),把很多地方都用到的东西,都放在这里 2.store存储的东西不能直接修改,只能通过commit提交

1.使用

  1. //main.js
  2. import store from store.js
  3. const app=new Vue({
  4. ...App,
  5. store
  6. })
  7. //单文件引用放在单文件的store选项里
  8. const app = new Vue({
  9. el: '#app',
  10. // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  11. store,
  12. components: { Counter },
  13. template: `
  14. <div class="app">
  15. <counter></counter>
  16. </div>
  17. `
  18. })
  19. //store.js
  20. import vue form 'vue'
  21. import vuex form 'vuex'
  22. vue.use(vuex)
  23. const store=new vue.Store({
  24. state:{}
  25. getters:{}
  26. mutations:{}
  27. ...
  28. })
  29. 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’])

  1. //getter.js
  2. export default{
  3. setStr(state){//传入state里的数据,默认第一个参数就是
  4. state.str//获取state种得数据
  5. }
  6. }

mutations:

是一个同步事务,异步操作会调试有问题 类似公共的方法,使用在methods中,…mutations([‘run’]),和正常方法一样使用 传参,默认接收第一个参数是state,第二个参数是对象{} store.commit(’函数名’),也可以直接提交调用 一般这个里面只写方法

  1. //mutations.js里
  2. mutationsfunction(state,{})
  3. //调用地方
  4. import {mapMutations} from 'vuex'
  5. methods:{
  6. ...mapMutations(['mutationsfunction']) //添加到方法里
  7. this.mutationsfunction({}) //引用库里的方法
  8. }

小应用
  1. //定义常量 mutations-types.js
  2. export count HOME="HOME"
  3. //mutations.js
  4. [HOME]{}

Action

提交的是mutation 可以包含异步操作

  1. //调用地方
  2. import {mapActions} from 'vuex'
  3. function({commit},obj)

Modules

仓库更明晰

  1. //store/index.js
  2. export default new Vuex.Store({
  3. modules:{
  4. list
  5. home
  6. }
  7. })
  8. //引用
  9. ...mapState({
  10. str:state=>state.list.str
  11. })