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
 })
发布了9 篇原创文章 · 获赞 2 · 访问量 68

猜你喜欢

转载自blog.csdn.net/pig_is_duck/article/details/105001496
今日推荐