Vuex语法使用

196 阅读1分钟
  • vue官方提供的独立于组件体系之外的,管理公共数据的工具

vuex单词.png vuex格式.png

1.store 保存公共数据

  • 格式
  state() {
    return {
       属性名: 属性值 
    }
  }
  • 使用公共数据
  1. 在任意组件中,通过this.$store.state.属性名来访问。
  2. 在模板中,则可以省略this而直接写成: {{$store.state.属性名}}
  3. state是响应式的: 如果修改了数据,相应的在视图上的值也会变化。

2.mutations 修改

  • 通过调用mutations来修改定义在state中的公共数据。
  • 第一个参数是必须的,表示当前的state。在使用时不需要传入
  • 第二个参数是可选的,表示形参,是可选的。在使用时要传入的数据
  mutations:{
    // 每一项都是一个函数,可以声明两个形参
    mutation名1 (state,形参) {
  
    },
    mutation名2 (state,形参) {
  
    }
   }

使用格式

this.$store.commit('mutation名', 实参)

vuex3.png

3.actions axios发异步请求

  actions: {
    //操作 store 所有项 一般用来发axios
    // context 查看 store 所有项必写
    action的名字 (context, 形参) {
      // 1. 发异步请求, 请求数据
      
      // 2. commit调用mutation来修改数据
            context.commit('mutation名', 实参)
    }
  }

在组件中通过this.$store.dispatch('actions的名字', 参数)来调用action

vuex3.png

4.getters 计算

  getters: {
    // state 就是上边定义的公共数据state
    getter的名字1: (state) {
      return 要返回的值
    }
  }

使用格式

在组件中通过:$store.getters.getter的名字 来访问

5.modules 模块拆分

格式

export default new Vuex.Store({
  // state: 用来保存所有的公共数据
  state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: {
    模块名1: {
        // namespaced为true,则在使用mutations时,就必须要加上模块名
      	namespaced: true, 
        state: {},   
  	getters: {},
  	mutations: {},
  	actions: {},
  	modules: {}
    },
    模块名2: {
        // namespaced不写,默认为false,则在使用mutations时,不需要加模块名
  	state: {},
  	getters: {},
  	mutations: {},
  	actions: {},
        modules: {}
    }  
  }
})

vuex 拆分模块.png

拆分模块.png

6.Vuex-辅助函数mapState来使用公共数据等等

  • mapState是第一个函数 会返回一个对象
  • 映射 需要导入
// 1. 导入辅助函数mapState,它是在vuex中定义的一个工具函数。
//  es6 按需导入 import { mapState } from 'vuex' 
import { mapState } from 'vuex'

computed: {
   // 说明1: ...对象 是把对象展开,合并到computed
   // 说明2: mapState是一个函数 
   //  ['数据项1', '数据项2']
   ...mapState(['xxx']),
   ...mapState({'新名字': 'xxx'})
}
  • 使用
this.xxx
{{xxx}}
  • 其他辅助函数 使用与上面同理 image.png

如何使用modules中的state

  • 直接使用: this.$store.state.模块名.xxx;
  • map辅助函数:
computed: { 
  ...mapState('模块名', ['xxx']), 
  ...mapState('模块名', {'新名字': 'xxx'})
}