vuex的语法功能和使用介绍

246 阅读2分钟

vuex 是 vue提供的状态管理工具

数据管理工具 => 管理的是公共的数据

一. state 提供数据(通用的数据)
  const store = new Vuex.Store({
  //状态 => 数据
  //state类似data提供数据的 且是响应式的(数据变化,视图自动更新)
  //不同之处:state的提供的数据是公开的,大家的  data的数据是组件内部私有的!!!
        state: {
          xxx: xxx
          desc:'vue不难'
        }
      })
  1. 模板使用数据
{{ this.$store.state.xxx }}
  1. 自己提供计算属性 {{ xxx }}
 xxx() {
          return this.$store.state.xxx
        }

3.mapState 辅助函数 帮你写了计算属性 {{ xxx }}

import { mapState } from 'vuex'
        ...mapState(['xxx', 'desc'])
二.mutations 提供修改数据的方法
        const store = new Vuex.Store({
          state: {
            xxx: xxx
          },
          //存放修改数据的方法
          mutations: {
          //所有方法默认都会接收一个state形参
          //一个数据的传参
            fn(state, 一个参数) {
              state.xxx = xxx
            },
            多个数据的传参
            Fn(state,{xxxx,xxxxx}){
            console.log(xxxxx)
            state.xxx += xxxx
            }
          }
        })
        
三.如何在组件内修改数据(提交mutation)
方法1.
       this.$store.commit('mutation名字', 1个参数)

方法2.
     //引入mapMutations 辅助函数 帮你提交mutation
         import { mapMutations } from 'vuex'
          ...mapMutations(['mutation名字'])
             this.xxxx()
            
        1.组件不能直接修改仓库的数据,违背单向数据流
        2.vuex也遵循单向数据流(父组件的数据会自动向下流动,
        影响到所有的子组件)
        3.仓库中的数据不能随便让别人改动,而是通知仓库,让仓库自己改,自动           
        向下流动,影响别人
四.严格模式的开启
const store = new Vuex.Store({
  ...
  // 开启严格模式, 必须遵循单向数据流, 只能通过mutation修改数据
  strict: true,
})
五.核心概念-actions: 封装异步操作
const store = new Vuex.Store({
          state: {
            xxx: xxx
          },
          //存放修改数据的方法
          mutations: {
          //所有方法默认都会接收一个state形参
            fn(state, 一个参数) {
              state.xxx = xxx
            }
          },
          //封装异步操作
          actions: {
            fnAsync(context) {
              setTimeout(() => {
                context.commit('mutation名字')
              }, 2000)
            }
          }
        })
六.组件中触发actions:
方法1.
        this.$store.dispatch('actions名字')
方法2.
        ...mapActions(['actions名字'])  this.xxx()
七. 核心概念-getters 相当于就是state的计算属性
   const store = new Vuex.Store({
          state: {
            xxx: xxx
          },
          //存放修改数据的方法
          mutations: {
            fn(state, 一个参数) {
              state.xxx = xxx
            }
          },
          //封装的异步操作
          actions: {
            fnAsync(context) {
              setTimeout(() => {
                context.commit('mutation名字')
              }, 2000)
            }
          },
          //相当于是state的计算属性
          getters: {
            bestCount(state) {
              return state.count + 100
            }
          }
        })
八.模板中使用:
方法1.
       $store.getters.xxx
方法2.       
       ...mapGetters(['xxx'])  {{ xxx }}

九. 模块化module-定义模块化准备state
const store = new Vuex.Store({
          state: {
            xxx: xxx
          },
          //存放修改数据的方法
          mutations: {
            fn(state, 一个参数) {
              state.xxx = xxx
            }
          },
          //封装的异步操作
          actions: {
            fnAsync(context) {
              setTimeout(() => {
                context.commit('mutation名字')
              }, 2000)
            }
          },
          //相当于state的计算属性
          getters: {
            bestCount(state) {
              return state.count + 100
            }
          },
          //定义模块
           modules: {
            模块名: {
          //命名空间,开启以后,模块内的mutations actions getters是注册        在模块内局部的方法!!!
              namespaced: true,  
              state: {},
              mutations:{},
              actions:{},
              getters:{}
            }
          }
        })
          

十.局部注册模块
        this.$store.commit('模块名/mutations名字')
        ...mapMutations('模块名' ,['mutations名字'])

        this.$store.dispatch('模块名/actions名字')
        ...mapActions('模块名' ,['actions名字'])

        1. $store.state.模块名.xxx
        2. ...mapState(['setting'])
        3. ...mapState('setting', ['title'])
十一.模块中-mapMutations -mapActions -mapState 的使用
const state = {
  title: '标题',
  desc: '不错',
}
// 默认模块内的mutations actions getters是注册在全局的
const mutations = {
  changeTitle(state, newTitle) {
    console.log('setting title 修改了')
    state.title = newTitle
  },
}

// this.$store.dispatch('setting/changeTitleAsync', '新标题')
// ...mapActions('setting', ['changeTitleAsync'])   this.changeTitleAsync('新标题')
const actions = {
  changeTitleAsync(context, newTitle) {
    setTimeout(() => {
      // 模块内提交自己的mutation 直接写!!
      context.commit('changeTitle', newTitle)
    }, 1000)
  },
}
const getters = {}

export default {
  // 开启以后, 模块内的mutations actions getters是注册在模块内局部的方法!!!
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
}

十二.模块中-mapState的使用补充

import { mapState, mapMutations } from 'vuex'
export default {
  computed: {
    // 映射全局的数据
    ...mapState(['testObj', 'setting']),
    // 映射setting模块的数据
    ...mapState('setting', ['title', 'desc']),
  },
}

十三.总结:

  vuex是一个 状态管理工具,数据管理工具。集中管理vue中通用的数据。
const store = new Vuex.Store({
  核心概念:
  //state状态(数据) 状态即数据
  //state类似于data提供数据的,响应式的(驱动)
  //不通点:state管理的是通用的 公共的数据,data的数据是组件内部私有的
    1. state 
       state: {
         xxx: xxx
       }
      
       this.$store.state.xxx
       ...mapState(['xxx'])
//提供同步修改数据的方法
    2. mutations  
       (1) 所有对于state的修改,必须经过mutation
       (2) 重要的原则:mutations函数必须是同步的操作,同步的操作才好监测,才能时光旅行
       mutations: {
         fn (state, 一个参数) {
           state.xxx = xxx
         }
       }

       this.$store.commit('mutation名字', 一个参数)
       ...mapMutations(['mutation名字'])
//actuons是用来封装异步操作(请求,延时器),内部还是得提交mutation
    3. actions 
       actions: {
         fnTest (context) {
           // 异步操作
           setTimeout(() => {
              // 提交mutation
              context.commit(mutation名字, 传参)
           }, 1000)
         }
       }

       this.$store.dispatch('action名字', 一个参数)
       ...mapActions(['action名字'])

//data和computed依赖data产生的其他数据 关系 和state 以及      getters的关系一样
    4. getters 
       getters: {
         total (state) {
           return state.xxx + 10
         }
       }

       this.$store.getters.xxx
       ...mapGetters(['getters名字'])
 //严格模式:(一旦开启,所有不规范的操作都会报错,必须要求你通过提交mutation的方式去修改数据-遵循单向数据流)
 strict:true)}
    5. modules 分模块,将来项目一旦复杂了,肯定会分模块,且防止命名冲突,会加上namespaced: true
       modules: {
         模块名: {
           namespaced: true,
           state: {},
           mutations: {},
           actions: {},
           getters: {}
         },
         模块名: {
           namespaced: true,
           state: {},
           mutations: {},
           actions: {},
           getters: {}
         }
       }

       如何获取 state (getters)
       1. this.$store.state.模块名.xxx
       2. ...mapState(['模块名']) 将一整个模块的state对象都拿过来
       3. ...mapState('模块名', ['xxx', 'xxx'])

       如何使用 mutations (actions)
       1. this.$store.commit('模块名/mutation名字', 一个参数)
       2. ...mapMutations('模块名', ['mutation名字'])
          
          // 可以重命名
          ...mapMutations('模块名', {
            新的方法名: 'mutation名字'
          })
```