vuex基本使用

1. State:提供唯一公共数据源, 所有需要共享的数据都要统一放到Store的State中进行存储。

// 创建store数据源, 提供唯一公共数据

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

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

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

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

// 从vuex中按需引入mapState函数

import { mapState } from "vuex"

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

// 将全局数据, 映射为当前组件的计算属性

computed: {
    ...mapState(["num"])
}

计算属性的使用也就是在需要这个值的地方{{  num }} 就可以了。

2.Mutation:用于变更Store中的数据 (不能直接通过$store修改数据)

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

 mutation可以集中监控数据的变化, 方便后期的维护

// 定义mutation

const store = new Vuex.Store({
    mutations: {
        num(state){
            // 变更状态    
            state.num ++
        }
    }
})

在组件中调用mutation函数

// 触发mutation

methods:{
    handlel(){
        // 触发 mutations 的第一种方式
        this.$store.commit('num')
    }
}

触发mutations传递参数, step是外界传递进来的参数

// 定义mutation

const store = new Vuex.Store({
    mutations: {
        num(state, step){
            // 变更状态    
            state.num += step
        }
    }
})
// 触发mutation

methods:{
    handlel(){
        // 触发 mutations 的第一种方式
        this.$store.commit('num', 2)
    }
}

 触发mutations的第二种方式:

// 从vuex中按需导入Mutations函数

import { mapMutations } from 'vuex'

将需要的mutations函数, 映射为当前组件的methods方法

methods:{
    ...mapMutations(['num'])
}

3.Action: 触发actions异步任务时携带参数

// 定义Action


const store = new Vuex.Store({
    actions: {
        numAsync(context, step){
            setTimeout(() => {context.commit('num', step)}, 1000)
        }
    }
})
// 触发Action

methods:  {
    handle(){

        // 在调用 dispatch函数,
        // 触发actions时携带参数
        this.$store.dispatch('numAsync', 5)
    }

}

触发actions的第二种方式

// 从vuex中按需导入Actions函数

import { mapAction } from 'vuex'
// 触发

methods:{
    handlel(){
        ...mapActions(['numAsync'])
    }
}

 4. Getter: 对Store中的数据进行处理 形成新的数据,

不会修改State中的原始数据

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

// 定义Action


const store = new Vuex.Store({
    getters: {
        showNum: state => {
            return '......'
        }
    }
})

使用getters方式1:

this.$store.getters.名称

使用getters方式2:

import { mapGetters} from 'vuex'

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值