vuex状态管理工具的使用

vuex使用介绍

使用步骤

  • 下载vuex: npm i vuex -S
  • 创建store实例, 实现数据管理
  • store.js
import Vue from 'vue';
import Vuex from 'vuex';
// 创建store实例对象之前, 必须把vuex注册成vue的插件
Vue.use(Vuex);
const store=new Vuex.Store({
    state:{
        comments:[]
    },
    mutations:{
        // 删除评论
        delComment (state,id) {
            state.comments=state.comments.filter(item=>item.id!=id)
        },
        // 新增评论
        addComment(state,comment){
            state.comments.unshift(comment);
        },
        // 获取默认评论列表
        getComments(state,comments){
            state.comments=comments
        }
    },
    actions:{
        // 异步获取默认的评论列表
        // getInitComments({dispatch, commit, getters})=>commit('getComments',comments);
        getInitComments(context){       
            const comments=[{
                id: 1,
                content: "人生若只如初见, 又何须伤感别离",
                author: "duans",
                posttime: new Date("2019/03/08").toLocaleDateString()
            },
            {
                id: 2,
                content: "若一切都已云烟成雨, 我能否变成淤泥,再一次沾染你?",
                author: "duans",
                posttime: new Date().toLocaleDateString()
            }]
            // 通过延时定时器模拟异步请求
            setTimeout(() => {
                context.commit('getComments',comments);
            }, 2000);
            
        }
    },
    getters:{
        // 计算评论数量
        commentsCount:state=>{
            return state.comments.length
        }
    }
});

export default store

  • 启用modules模块
import Vue from 'vue';
import Vuex from 'vuex';
// 创建store实例对象之前, 必须把vuex注册成vue的插件
Vue.use(Vuex);
const store = new Vuex.Store({
    modules: {
        // 评论模块
        comments: {
            // 启用单独的命名空间(默认注册在全局命名空间)
            namespaced: true,
            state: {
                comments: []
            },
            mutations: {
                // 删除评论
                delComment(state, id) {
                    state.comments = state.comments.filter(item => item.id != id)
                },
                // 新增评论
                addComment(state, comment) {
                    state.comments.unshift(comment);
                },
                // 获取默认评论列表
                getComments(state, comments) {
                    state.comments = comments
                }
            },
            actions: {
                // 异步获取默认的评论列表
                getInitComments({ commit }) {
                    const comments = [{
                        id: 1,
                        content: "人生若只如初见, 又何须伤感别离",
                        author: "duans",
                        posttime: new Date("2019/03/08").toLocaleDateString()
                    },
                    {
                        id: 2,
                        content: "若一切都已云烟成雨, 我能否变成淤泥,再一次沾染你?",
                        author: "duans",
                        posttime: new Date().toLocaleDateString()
                    }]
                    // 通过演示定时器模拟异步请求
                    setTimeout(() => {
                        commit('getComments', comments);
                    }, 2000);

                }
            },
            getters: {
                // 计算评论数量
                commentsCount: state => {
                    return state.comments.length
                }
            }
        }
    }

});

export default store
  • store实例挂载到vue实例对象上(这样在vue组件中就可以通过this.$store来调用store对象操作数据)
  • main.js
// main.js
import Vue from 'vue'
import App from './App'
// 导入vuex实例对象store
import store from './store'
Vue.config.productionTip = false
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  store
})

State

在组件中调用

this.$store.state.comments
// 如果使用了modules模块, 并且启用了单独的namespace命名空间
this.$store.state.moduleName.comments

使用mapState分发state

import { mapState } from "vuex";
export default {
    computed:{
        // 将comments映射成this.$store.state.comments
        ...mapState(['comments'])
        // 如果使用了modules模块, 并且启用了单独的namespace命名空间
        ...mapState('moduleName',['comments'])
    }
}

Getter

在组件中调用

this.$store.getters.commentsCount
// 如果使用了modules模块, 并且启用了单独的namespace命名空间
this.$store.getters['moduleName/commentsCount']

使用mapGetters分发getters

import { mapActions } from "vuex";
export default {
    computed:{
        // 将commentsCount映射成this.$store.getters.commentsCount
        ...mapGetters(['commentsCount'])
        // 如果使用了modules模块, 并且启用了单独的namespace命名空间
        ...mapGetters('moduleName',['commentsCount'])
    }
}

Mutation

  • mutations中的方法只能是同步方法

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:

在组件中调用

const comment={
    id:1,
    author:'zs',
    content:'张三的歌',
    posttime:new Date()
}
// 通过commit方法触发addComment()
this.$store.commit('addComment',comment)
// mutations的另外一中提交方式
this.$store.commit({type: 'addComment',comment})
// 如果使用了modules模块, 并且启用了单独的namespace命名空间
this.$store.commit('ModuleName/addComment',comment)

使用mapMutations分发mutations

import { mapActions } from "vuex";
export default {
    methods:{
        // 将this.addComment()映射成this.$store.commit('addComment')
        // 将this.delComment()映射成this.$store.commit('delComment')
        ...mapMutations(['addComment','delComment'])
        // 如果使用了modules模块, 并且启用了单独的namespace命名空间
        ...mapMutations('moduleName',['addComment','delComment'])
    }
}

Action

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。

  • Action 类似于 mutation,不同在于:
    • Action 提交的是 mutation,而不是直接变更状态。
    • Action 可以包含任意异步操作

在组件中调用

this.$store.dispatch('getInitComments')
// 如果使用了modules模块, 并且启用了单独的namespace命名空间
this.$store.dispatch('ModuleName/getInitComments')

使用mapActions分发actions

import { mapActions } from "vuex";
export default {
    methods:{
        // 将this.getInitComments()映射成this.$store.dispatch('getInitComments')
        ...mapActions(['getInitComments'])
        // 如果使用了modules模块, 并且启用了单独的namespace命名空间
        ...mapActions('moduleName',['getInitComments'])
    },
    created(){
        // 通过异步请求,获取默认数据
        this.getInitComments()
    }
}

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 的状态

参考文档

Vuex官方文档

案例源码仓库地址

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,306评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,657评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,928评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,688评论 0 220
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,105评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,024评论 1 225
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,159评论 2 318
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,937评论 0 212
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,689评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,851评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,325评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,651评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,364评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,192评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,985评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,154评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,955评论 2 279

推荐阅读更多精彩内容

  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 2,908评论 0 7
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 3,076评论 0 6
  • 目录 - 1.什么是vuex? - 2.为什么要使用Vuex? - 3.vuex的核心概念?||如何在组件中去使用...
    我跟你蒋阅读 4,095评论 4 51
  • Vuex 是什么? Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有...
    skycolor阅读 787评论 0 1
  • ### store 1. Vue 组件中获得 Vuex 状态 ```js //方式一 全局引入单例类 // 创建一...
    芸豆_6a86阅读 698评论 0 3