Vuex系列状态管理篇--Vuex(2)之State

2、Vuex的项目配置

2.1、为什么要分开文件

分开Vuex文件有利于项目文件管理

2.2、项目文件分解图

在这里插入图片描述

  • 将Vuex的每个模块分解为以上几个文件
  • 总入口 index.js 代码为
import Vue from 'vue'
import Vuex from 'vuex'

import actions from "./actions";
import mutations from "./mutations";
import state from "./state";
import getters from './getters'
import user from "./modules/user"

Vue.use(Vuex)

export default new Vuex.Store({
state,
mutations,
actions,
getters,
modules: {
  user
}
})

3、Vuex–state

相当于一个数据仓库

在Vuex的state中定义的数据,可以在各个文件中拿到

3.1、在根Vuex下

  1. 定义
const state = {
 appName: 'duck'
}

export default state
  1. 获取
this.$store.state.appName

也可以使用 vuex 的 mapState 获取

import { mapState } from "vuex";  // 先导入方法

// ...mapState([
//     'appName'
// ])
// 或是这样

...mapState({
    appName: state => state.appName,
})

3.2、在模块下

1.定义(在模块文件下定义)

const state = {
userName: 'pig'
}
const mutations = {}
const actions = {}
const getters = {}
export default {
state,
mutations,
actions,
getters
}
  1. 获取(this.$store.state.模块名.模块内定义的state)
this.$store.state.user.userName

也可以使用 vuex 的 mapState 获取

import { mapState } from "vuex";  // 先导入方法

 ...mapState({
     userName: state => state.user.userName
 })
  1. 若是在模块中设置了命名空间,可以使用其他方法
// 在模块文件中
export default {
  namespaced: true,  // 命名空间,true
  state,
  mutations,
  actions
}
// 在使用的文件中
import { createNamespacedHelpers } from "vuex";
const { mapState } = createNamespacedHelpers('user')

 ...mapState({
     userName: state => state.userName  // 不需要写模块名称了
  })

或是

import { mapState } from "vuex";

...mapState('user', {  // 传入开启命名空间的模块名
     userName: state => state.userName
 })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值