vuex的使用

vuex 核心概念
State 提供唯一公共数据源,所有的共享数据都要统一放到Store 的State 中存储

前置条件 已安装有vuex
在store 新建modules 后在index 中引入 (分模块,业务多之后会更清晰)
index.js 中的js 代码如下:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 自动查找模块
const modules = {}
const files = require.context("./modules",false,/\.js$/)
files.keys().forEach(path => {
    const key = path.replace(/(\.\/|\.js)/g,'');
    if(key != 'index'){
        modules[key] = files(path).default
    }
});
export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules
})

1 读取vuex state 中数据的几种方法
1.1 <h2>{{ $store.state.account.num }}</h2> <h1>{{ num }}</h1>
页面展示效果

1.2 引入mapState 通过计算属性的方式(通过计算属性将state 的数据映射为 data 中的数据)

import {  mapState } from "vuex";
  computed: {
     ...mapState("account", ["num"]),  方法一
    num(){
      return this.$store.state.account.num 方法二
    }
  },

2 改变State 中的数据
如在modules 中 已有 account.js

export default {
    namespaced: true,
  state: {
    num:2
  },
  getters: {
  },
  mutations: {   //用于变更state 中的数据
    add(state,params) {
      state.num  +=  params
    },
  },
  actions: {   // 用于处理异步任务
  },
  modules: {
  }
}

2.1 this.$store.commit('account/add',1) (实现传参+1)
2.2 通过导入MapMutations 函数实现 将MapMutations 函数 映射为组件的 methods 方法

import { mapMutations, mapState } from "vuex"     ;
 methods:{
    ...mapMutations("account", ["add"]),
    }
    test(){
	this.add(5)  //映射进来之后即可以像调用普通方法那样调用
		}

3 执行异步操作

 actions: {  
    addAsync(context){  // context 相当于new了一个实例对象 里面有commit
      // 在action 不能直接修改
      setTimeout(async()  => {
        await context('add',50)
      }, 1500);
    }
  },
this.$store.dispatch('account/addAsync')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值