主页

Vuex 概述

Vuex 是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享

使用 Vuex 统一管理状态的好处

  1. 能够在 vuex 中集中管理共享的数据,易于开发和后期维护
  2. 能够高效的实现组件之间的数据共享,提高开发效率
  3. 存储在 vuex 中的数据都是响应式的,能够实现保持数据与页面的同步

Vuex 的基本使用

1. 安装 vuex 依赖包

npm install vuex --save

2. 导入 vuex 包

import Vuex from 'vuex'
Vue.use(Vuex)

3. 创建 store 对象

const store = new Vuex.Store({
    // state 中存放的就是全局共享的数据
    state: {
        count: 0
    }
})

4. 将 store 对象挂载到 vue 实例中

new Vue({
    el: '#app',
    router,
    // 将创建的共享数据对象,挂载到 Vue 实例中
    // 所有的组件,就可以直接从 store 中获取全局的数据
    store
})

Vuex 的核心概念

State

State 提供唯一的公告数据源,所有共享的数据都有统一放到 Store 的 State 中进行存储

// 创建 store 数据源,提供唯一公共数据
const store = new Vuex.Store({
    state: {
        count: 0
    }
})

组件中访问 State 中数据的第一种方式:

this.$store.state.全局数据名称

组件中访问 State 中数据的第二种方式:

// 1. 从 vuex 中按需导入 mapState 函数
import { mapState } from 'vuex'

通过刚才导入的 mapState 函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性:

computed: {
// 2. 将全局数据,映射为当前组件的计算属性
    ...mapState(['count'])
}

Mutation

Mutation 用于变更 Store 中的数据

  1. 只能通过 mutation 变更 store 数据,不可以直接操作 store 中的数据
  2. 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
// 在 vuex 中定义 Mutation
const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        add(state) {
            // 变更状态
            state.count++
        }
    }
})
// 在组件中触发 mutation
methods: {
    add() {
        // 触发 mutations 的第一种方式
        this.$store.commit('add')
    }
}

可以再 触发 mutations 时传递参数:

// 在 vuex 中定义 Mutation
const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        addN(state, step) {
            // 变更状态
            state.count += step
        }
    }
})
// 在组件中触发 mutation
methods: {
    add() {
        // 在调用 commit 函数,触发 mutations 时携带参数
        this.$store.commit('addN', 3)
    }
}

this.$store.commit() 是触发 mutations 的第一种方式,触发 mutations 的第二种方式是:

// 1. 从 vuex 中按需导入 mapMutations 函数
import { mapMutations } from 'vuex'

通过刚才导入的 mapMutations 函数,将需要的 mutations 函数,映射为当前组件的 methods 方法:

// 2. 将指定的 mutations 函数,映射为当前组件的 methods 函数
methods: {
    ...mapMutations(['add', 'addN'])
    // 传参
    自定义事件名() {
        this.addN(3)
    }
}

Action

Action 用于处理异步操作
如果通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在 Action 中还是要出发 Mutation 的方式间接变更数据

// 定义 Action
const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        add(state) {
            state.count++
        }
    },
    actions: {
        addAsync(context) {
            setTimeout(() => {
                context.commit('add')
            }, 1000)
        }
    }
})
// 触发 Action
methods: {
    add() {
        // 触发 actions 的第一种方式
        this.$store.dispatch('addAsync')
    }
}

触发 actions 异步任务时携带参数

// 定义 Action
const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        addN(state, step) {
            state.count += step
        }
    },
    actions: {
        addNAsync(context, step) {
            setTimeout(() => {
                context.commit('addN', step)
            }, 1000)
        }
    }
})
// 触发 Action
methods: {
    addN() {
        // 在调用 dispatch 函数,触发 actions 时携带参数
        this.$store.dispatch('addNAsync', 5)
    }
}

触发 Action 函数的第二种方式:

// 1. 从 vuex 中按需导入 mapActions 函数
import { mapActions } from 'vuex'

通过刚才导入的 mapActions 函数,将需要的 actions 函数,映射为当前组件的 methods 方法:

/// 2. 将指定的 actions 函数,映射为当前组件的 methods 方法
methods: {
    ...mapActions(['addAsync', 'addNAsync'])
}

Getter

Getter 用于对 Store 中的数据进行加工处理成新的数据

  1. Getter 可以对 Store 中已有的数据进行加工处理之后形成新的数据,类似 Vue 的计算属性
  2. Store 中数据发生变化,Getter 的数据也会跟着变化
// 定义 Getter
const store = new Vuex.Store({
    state: {
        count: 0
    },
    getters: {
        showNum(state) {
            return '当前最新的数量是【'+ state.count +'】'
        }
    }
})

使用 getters 的第一种方式:

this.$store.getters.名称

使用 getters 的第二种方式:

import { mapGetters } from 'vuex'

computed: {
    ...mapGetters(['showNum'])
}

vuex 持久化

默认存储所有 state 数据到 localStorage

npm install vuex-persistedstate --save

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
  state: { },
  getters: { },
  mutations: { },
  actions: { },
  modules: { },
  // 配置 vuex 插件
  plugins: [
    createPersistedState()
  ]
})

存储所有 state 数据到 sessionStorage

import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
export default createStore({  
    state: { },  
    mutations: { },  
    actions: { },  
    modules: { },  
    plugins: [    
        // 把 vuex 的数据存储到 sessionStorage    
        createPersistedState({      
            storage: window.sessionStorage,    
        }),  
    ],
})

存储指定的 state 数据

import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
export default createStore({  
    state: { },  
    mutations: { },  
    actions: { },  
    modules: { },  
    plugins: [    
        // 把 vuex 的数据存储到 sessionStorage    
        createPersistedState({      
            storage: window.sessionStorage,      
            reducer(val) {        
                return {          
                    // 只存储 state 中的 userData          
                    userData: val.userData        
                }      
            }    
        }),  
    ],
})

API

  • key:存储持久状态的 key(默认 vuex)
  • paths:部分持续状态的任何路径的数组。如果没有路径给出,完整的状态是持久的。(默认:[])
  • reducer:一个函数,将被调用来基于给定的路径持久化的状态。默认包含这些值。
  • subscriber:一个被调用来设置突变订阅的函数。默认为 store => handler => store.subscribe(handler)
  • storage:而不是(或与)getState 和 setState。默认为 localStorage。
  • getState:将被调用以重新水化先前持久状态的函数。默认使用 storage。
  • setState:将被调用来保持给定状态的函数。默认使用 storage。
  • filter:将被调用来过滤将 setState 最终触发存储的任何突变的函数。默认为 () => true

Vuex

版权属于:Joe
作品采用:本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
1

目录

来自 《Vuex-基本使用》
评论

qiaofugui

博主很懒,啥都没有
188 文章数
14 评论量
3 分类数
191 页面数
已在风雨中度过 2年131天23小时54分