vuex介绍
- state,驱动应用的数据源;相当于组件中的data
- view,以声明方式将 state 映射到视图;相当于组件中的template
- actions,响应在 view 上的用户输入导致的状态变化。相当于组件中的methods
安装
vue add vuex通过这种方式安装会自动配置相关信息npm install vuex --save通过这种方式安装,要自己配置vuex的相关信息
使用
- Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
- 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
通过npm install vuex —save安装:
先main.js文件中导入并注册store
import Vue from 'vue'import App from './App.vue'import store from './store'Vue.config.productionTip = falsenew Vue({// 为了在 Vue 组件中访问 this.$store property,你需要为 Vue 实例提供创建好的 storestore,render: h => h(App)}).$mount('#app')
在创建一个.js文件实例化一个Store,并导出他
import Vue from 'vue'import Vuex from 'vuex'// 通过vue.use注册VuexVue.use(Vuex)// 实例化一个store对象export default new Vuex.Store({// state类似于组件中的data,用来存放对象// state中的对象只能通过mutations中的函数修改state: {count:0},// getters类似于组件中的computed对象,用来处理数据getters: {},// mutations和actions类似于组件中的methods对象// mutations中必须使用同步函数,mutations中的函数用于修改state中的对象mutations: {increment (state) {state.count++}},// actions中的函数可以返回一个Promise,这也说明actions中可以使用异步函数的。// actions中的函数不能直接修改state,需要调用mutations中的函数来修改。// 通过commit调用mutations中的函数actions: {},// 模块对象。每个模块相当于一个Store的实例化对象modules: {}})
获取数据,修改数据
获取数据
在组建方法中:this.$store.state.xxx
在标签中:$store.state.xxx或this.$store.state.xxx
<template><div>//获取数据时可以加this,也可以不加,通过$store.state.xxx获取store中的数据<div>{{this.$store.state.count}}</div><div>{{$store.state.count}}</div></div></template><script>export default {mounted(){// 通过this.$store.commit的形式调用mutations中的increment函数修改state中的count对象this.$store.commit('increment')// 打印修改后的数据console.log(this.$store.state.count)}}</script>
State
Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源 (SSOT(opens new window))”而存在。这也意味着,每个应用将仅仅包含一个 store 实例。单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。
存储在 Vuex 中的数据和 Vue 实例中的 data 遵循相同的规则
在组件中获取vuex的state
export default {mounted(){// 通过this.$store.commit的形式调用mutations中的increment函数修改state中的count对象this.$store.commit('increment')// 打印修改后的数据console.log(this.$store.state.count)}}
mapState辅助函数
传入一个对象作为mapState参数
// mapState时state的辅助函数// 传入一个对象computed:mapState({// 这里可以使用箭头函数,通过函数将state中的对象返回给count// 这样就可以在组件中通过count来显示state中的count对象的内容了// 因为时响应式的所以数据会实时更新count: function(state) {return state.count},// 通过别名方式获取state中的对象// 这里的'count' 等同于 `state => state.count`Acount:'count',// 为了能够使用 `this` 获取局部状态,必须使用常规函数getLocalData(state){return state.count + this.a}}),
传入一个数组作为mapState参数
// 当映射的计算属性的名称与 state 的子节点名称相同时,可以给 mapState 传一个字符串数组computed:mapState([// 映射 this.count 为 store.state.count'count']),
对象展开符
computed:{// 通过对象展开符将mapState返回的对象展开...mapState({count: state => state.count,Acount:'count',getLocalData(state){return state.count + this.a}})},
getters
// 处理数据,和组件中的computed类似// 通过getters将数据处理并保存,在组件中通过this.$store.getters.xxx获取对应的处理结果// this.$store.getters.newName --> undefined123123(undefined是因为没有name)getters:{//第二个参数是一个gettersnewName(state,get){// 可以调用另一个getters// get 代表gettersreturn state.name+ "123" + get.newName2;},newName2(state) {return "123";}}
获取getters中的数据
mounted(){console.log(this.$store.getters.newName)}
通过方法访问
你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。
getters: {getTodoById: function(state) {return (id) =>{// todos是一个数组return state.todos.find(todo => todo.id === id)}}}
使用
mounted(){this.$store.getters.getTodoById(2)}
mapGetters辅助函数
使用方法和mapState类似
computed:{// 起别名// ...mapGetters({// someohter:'newName',// })//直接映射...mapGetters(['newName'])},
mutations
Mutation 必须是同步函数
接收参数
mutations: {// 在大多数情况下,载荷应该是一个对象,increment (state,payload) {state.count++;console.log(payload);}},
传入参数
参数2可以是一个对像,也可以是多个参数
mounted(){this.$store.commit('increment',{"a":12,"b":21})}
对象风格的提交方式
mounted(){this.$store.commit({// type属性对应mutations中的方法type:'increment',//剩下的属性都是参数,全部会被放到payload对象中amount: 10,account:"hao123"})}
Mutation 需遵守 Vue 的响应规则
既然 Vuex 的 store 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:
- 最好提前在你的 store 中初始化好所有所需属性。
- 当需要在对象上添加新属性时,你应该
- 使用 Vue.set(obj, ‘newProp’, 123), 或者
- 以新对象替换老对象。例如,利用对象展开运算符(opens new window)我们可以这样写:
state.obj = { ...state.obj, newProp: 123 }
使用常量替代 Mutation 事件类型
在store的js文件中导入export const SOME_MUTATION = 'SOME_MUTATION';export const mutations= {// 在大多数情况下,载荷应该是一个对象,increment (state,payload) {state.count++;console.log(payload);console.log(state)}}
在组件中提交 Mutation
mapMutations 辅助函数
methods:{...mapMutations(['increment'// 将 `this.increment()` 映射为 `this.$store.commit('increment')`]),...mapMutations({// 别名add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`})}
使用
mounted(){this.increment();this.add()}
action
可以在 action 内部执行异步操作
使用
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。
actions: {// 这里的context相当于是storeincrement (context) {//commit中的increment是mutations中的函数context.commit('increment')}},
实践中,我们会经常用到 ES2015 的 参数解构(opens new window)来简化代码(特别是我们需要调用 commit 很多次的时候):
actions: {// 通过解构获取到commit对象--》const {commit} = storeincrement ({ commit }) {commit('increment')}}
触发action
mounted(){// 触发action中的方法this.$store.dispatch('increment')}
Actions 支持同样的载荷方式和对象方式进行分发
mounted(){// 以载荷形式分发this.$store.dispatch('increment',{"a":123,"b":456})// 以对象形式分发this.$store.dispatch({type: 'increment',"a":123,"b":456})}
接收方式也是一样的
actions: {increment (context,payload) {context.commit('increment',payload)}},
在组件中分发 Action
mapActions 辅助函数
methods:{...mapActions (['increment',]),...mapActions ({add:'increment',})},
store.dispatch
store.dispatch返回一个Promise
action中的函数也可以返回一个Promise
actions: {actionA ({ commit }) {return new Promise((resolve, reject) => {setTimeout(() => {commit('someMutation')resolve()}, 1000)})}}store.dispatch('actionA')返回一个Promise
actions中的函数亦可以使用dispatch触发另一个action
actions: {// ...actionB ({ dispatch, commit }) {return dispatch('actionA').then(() => {commit('someOtherMutation')})}}
使用async await处理异步函数
actions: {async actionA ({ commit }) {commit('gotData', await getData())},async actionB ({ dispatch, commit }) {await dispatch('actionA') // 等待 actionA 完成commit('gotOtherData', await getOtherData())}}
module
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
const moduleA = {state: () => ({ ... }),mutations: { ... },actions: { ... },getters: { ... }}const moduleB = {state: () => ({ ... }),mutations: { ... },actions: { ... }}const store = new Vuex.Store({modules: {a: moduleA,b: moduleB}})store.state.a // -> moduleA 的状态store.state.b // -> moduleB 的状态
