Vuex的使用

Vuex

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

 

Vuex 的基本使用

1.安装依赖包

npm install vuex -S

2.导入包

import Vuex from 'vuex'

3.创建 store 对象

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

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

new Vue({
    el:'#app',
    render:h=>h(app),
    router,
    store
})

Vuex 的核心概念

组件访问 State 中数据的方式

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

  2. 从 vuex 中按需导入 mapState 函数

    import { mapState } from 'vuex'

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

    computed:{
        ...mapState(['count'])
    }

    Mutation

    Mutation 用于变更 Store 中的数据

    1. 只能通过mutation变更 Store 数据,不可以直接操作 Store 中的数据

    2. 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化

    3. 不要在 mutation 函数中 , 执行异步操作

const store = new Vuex.Store({
    state:{
        count:0
    },
    mutations:{
        add(state){
            //变更状态
            state.count++
            
            //如果传入其他参数
            add(state,step){
                state.count+=step
            }
        }
    }
})
// 触发mutation
methods:{
    headle1(){
        this.$store.commit('add')
    }
}
//如果传入多个参数
this.$store.commit('add',3)

Action

Action用于处理异步任务

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

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

传入多个参数,同Mutation

Getter

Getter 用于对Store 中的数据进行加工树立形成新的数据。

1.Getter 可以对 Store 中已有的数据加工处理后形成新的数据,类似Vue的计算属性

2.Store中数据发生变化,Getter 的数据也会跟着变化。

// 定义 Gettter
const store = new Vuex.Store({
    state:{
        count:0
    },
    getters:{
        showNum:state=>{
            return '当前最新的数量是【'+state,count+'】'
        }
    }
})

使用getters的第一种方式

this.$store.getters.名称

使用getters的第二种方式

import { mapGetters } from 'Vuex'
​
comoputed:{
    ...mapGetters(['showNum'])
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值