vuex的基础用法

前言

vuex在vuejs构建大型项目的时候,是必不可少的。网上对他的介绍很多,官网介绍的也很详细。但是自己还是想结合官网总结自己的一篇。

vuex 介绍

状态存储仓库,官网定义请走这里

vuex 使用

用之前下载依赖下,官网的脚手架最开始并没有推荐安装,所以还是老老实实下载... (如果下载不成功,那就用淘宝镜像吧,一毛一样...)

npm install vuex --save

这里按照官方文档,让我们来撩开vuex的围裙...

按照官网文档的介绍,vuex的核心概念包含有:State,Getter,Mutation,Action,Module 这五个...,下面将一一介绍他们的概念和用法。

  • 准备

在介绍下面五个模块前,我们先使用vue-cli脚手架创建一个项目,在src下,创建一个vuex文件,再在vuex文件里,创建一个store.js(可自定义,非必须) ,引入vue和vuex,初始化对象,在根目录注入,创建一个组件,就可以访问你访问的属性了...

// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
    count:0
}

const store = new Vuex.Store ({
    state
})

export default store


//main.js  在根组件注入,全局就可以访问到了

import Vue from 'vue'
import App from './App'
import router from './router'

import store from './vuex/store' // 引入


new Vue({
  el: '#app',
  router,
  store, // 注入
  components: { App },
  template: '<App/>'
})


// index.vue 组件里访问
<template>
    <div>
        {{count}}
        {{$store.state.count}}
    </div>
</template>
<script>
    import { mapState } from 'vuex'
    import store from 'vuex'
    export default {
        computed:{
            ...mapState({
                count:state => state.count
            })
            // ...mapState(['count']) 效果同上
        }
    }
</script>

这里访问store.js定义的count有两种方式,一种是使用this.$store.state.count,另外一种使用辅助函数mapState访问。(以下,将对store.js和index.vue扩展,默认vuex实例注入根组件)

  • State

    state 就是你自定义状态,就像组件里data钩子函数里定义的变量一样。第一个案例也做了简单的介绍。官网请走这里。 在实际中,我最多使用就是mapState辅助函数,在计算属性的钩子获取,后面也可以使用Getter替代...

  • Getter
    作用:防止重复性劳动。getter会缓存值,依赖改变,也会相应更新缓存值。getter接受state作为第一个参数,根据state的值,来修改值,然后暴露store.getter对象。

  //修改store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
    count:0
}
const getter = {
    getNum(state){
        return state.count;
    }
}
const store = new Vuex.Store ({
    state,
    getter
})
export default store
    
// 修改index.vue
    
<template>
    <div>
        {{getNum}}
        {{$store.getters.getNum}}
    </div>
</template>
<script>
    import { mapGetters } from 'vuex'
    import store from 'vuex'
    export default {
        computed:{
            ...mapGetters(['getNum']),
        },
    }
</script>

在div标签里,获取的值是一样,一个是直接获取(下面一个),不需要引入辅助函数。而另一需要借助辅助函数。当然getter有第二个参数,把其他getter作为参数来使用。(不能异步)

  • Mutation
    1. 更新store中的状态,只能以提交mutation的方式改变
    2. 每个mutation都有一个事件类型(type)和一个回调函数,当触发事件类型,调用该函数,就像原生的点击事件一样...
// 事件类型click,触发一个回调
$('#id').on('click',function(){
    alert('ok')
})

如果我们我们在commit之外,额外传递参数,就需要mutation的载荷(payload),载荷可以为一个值,也可以为一个对象。

下面我们来简单的例子,来看下mutation的使用

//点击按钮,实现累加的效果

// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
    count:0
}

<!--const getters = {-->
<!--    getNum(state){-->
<!--        return state.count;-->
<!--    }-->
<!--}-->

const mutations = {
    increment(state,payload){
        state.count += payload.amount;
    }
}

const store = new Vuex.Store ({
    state,
    <!--getters,-->
    mutations
})

export default store

// index.vue
<template>
    <div>
        {{ count }}
        <button @click="add">按钮</button>
    </div>
</template>
<script>
    import { mapState, mapMutations } from 'vuex'
    export default {
        computed:{
            ...mapState({
                count:state => state.count
            }),
        },
        methods:{
            ...mapMutations(['increment']),
            add(){
                this.$store.commit({
                    type:'increment',
                    amount:10
                })
            }
        }
    }
</script>

如上案例,根据对象提交载荷,实现页面每次累加10。

mutation 的事件类型可以用常量来替代,最大的好处就是提高代码的可阅读性,后面在做介绍。非常重要的一点是,mutation是同步函数,为了实时捕捉到state中的状态。但是没有异步,要它何用? 下面就是他的好基友action,两个用法一直,区别有,action提交mutation,不是直接改变状态,mutation是直接能改变状态了,action可以是异步操作。

action 接受一个和store实例具有相同属性和方法的context对象,但不是store实例对象。因为module,在module可以包含像content实例,但是store实例就只有一个。

const getters = {
    getNum(context){
        console.log(context)
        context.commit('increment')
    }
}

看看打印出的值


这个时候,我们可以解构下...

const getters = {
    getNum({commit}){
        commit('increment')
    }
}
// 效果和上面一毛一样

现在我们把整个代码贴一下,还是实现那个累加的效果

// index.vue 修改如下
<template>
    <div>
        {{ count }}
        <button @click="add">按钮</button>
    </div>
</template>
<script>
    import { mapState } from 'vuex'
    import store from 'vuex'
    export default {
        computed:{
            ...mapState({
                count:state => state.count
            })
        },
        methods:{
            add(){
                this.$store.dispatch({
                    type:'incrementAsync',
                    amount:10
                })
            }
        }
    }
</script>

// store.js 修改如下
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
    count:0
}

const getters = {
    getNum(state){
        return state.count;
    }
}
const mutations = {
    increment(state,payload){
        state.count += payload.amount;
    }
}

const actions = {
    incrementAsync({commit},payload){
        commit('increment',payload)
    }
}

const store = new Vuex.Store ({
    state,
    getters,
    mutations,
    actions
})

export default store

当前该组件分发action,使用this.$store.dispatch('xxx')来分发。当让我们最常用的还是用辅助函数mapActions,来改版下...

//index.vue

<template>
    <div>
        {{ count }}
        <button @click="add">按钮</button>
    </div>
</template>
<script>
    import { mapState, mapActions } from 'vuex'
    import store from 'vuex'
    export default {
        computed:{
            ...mapState({
                count:state => state.count
            })
        },
        methods:{
            ...mapActions(['incrementAsync']),
            add(){
                this.incrementAsync({
                    amount:10
                })
            }
        }
    }
</script>

// mapActions 也是支持载荷,我们也可以尝试下...

<template>
    <div>
        {{ count }}
        <button @click="incrementAsync({amount:10})">按钮</button>
    </div>
</template>
<script>
    import { mapState, mapActions } from 'vuex'
    import store from 'vuex'
    export default {
        computed:{
            ...mapState({
                count:state => state.count
            })
        },
        methods:{
            ...mapActions(['incrementAsync']),
        }
    }
</script>

// 和上面实现的效果是一样的,当没有载荷(其他参数),就可以在标签上直接绑定incrementAsync方法。

当前我们使用action最凸显的有点就是异步,我们可以使用setTimeout或者setInterval 来模拟下异步。

//这里我们只需要修改store.js里的acitons就可以了

const actions = {
    incrementAsync({commit},payload){
        setTimeout(() => {
            commit('increment',payload)
        },1000)
    }
}

// 每隔1秒钟,数字累加10

组合action,利用promise,async/await来实现按自己的要求action函数触发顺序。 具体查看vuex官网,介绍的很详细,这里就不多做介绍。

  • Module

vuex 可以将store分割成不同的模块,现在我们把上面案例分割成不同模块。在store.js 同级目录新建 actions.js、types.js、mutations.js、getter.js 来简单模拟下...

//store.js
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions'
import getters from './getters'
import mutations from './mutations'
Vue.use(Vuex)

const store = new Vuex.Store ({
    getters,
    actions,
    modules:{
        mutations
    }
})

export default store

// actions.js

import { ADDNUM } from './types'

const actions = {
    incrementAsync({commit},payload){
        setTimeout(() => {
            commit(ADDNUM,payload)
        },1000)
    }
}

export default actions

// types.js
export const ADDNUM = 'ADDNUM';

// mutations.js

import { ADDNUM } from './types';

const state = {
    count:0
}

const mutations = {
    [ADDNUM](state,payload){
        state.count += payload.amount;
    }
}

export default {
    state,
    mutations
}

//getter.js

const actions = {
    getNum(state){
        return state.mutations.count
    }
}
export default actions;


//index.vue

<template>
    <div>
        {{ getNum }}
        <button @click="add">按钮</button>
    </div>
</template>
<script>
    import { mapGetters, mapActions } from 'vuex'
    export default {
        computed:{
            ...mapGetters(['getNum'])
        },
        methods:{
            ...mapActions(['incrementAsync']),
            add(){
                this.incrementAsync({
                    amount:10
                })
            }
        }
    }
</script>

以上就是一个简单的demo,实现点击按钮,数字一秒后,以10数字叠加。

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

推荐阅读更多精彩内容

  • vuex是一个状态管理模式,通过用户的actions触发事件,然后通过mutations去更改数据(你也可以说状态...
    Ming_Hu阅读 2,034评论 3 3
  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 2,962评论 0 7
  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应...
    白水螺丝阅读 4,681评论 7 61
  • Vuex 的学习记录 资料参考网址Vuex中文官网Vuex项目结构示例 -- 购物车Vuex 通俗版教程Nuxt....
    流云012阅读 1,469评论 0 7
  • 系列文章:Vue 2.0 升(cai)级(keng)之旅Vuex — The core of Vue applic...
    6ed7563919d4阅读 4,564评论 2 58