Vuex模块化和命名空间namespaced实例演示

1. 目的:

让代码更好维护,让多种数据分类更加明确。

2. 修改store/index.js

store/index.js

const countAbout = {
  namespaced:true,//开启命名空间
  state:{x:1},
  mutations: { ... },
  actions: { ... },
  getters: {
    bigSum(state){
       return state.sum * 10
    }
  }
}

const personAbout = {
  namespaced:true,//开启命名空间
  state:{ ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    countAbout,
    personAbout
  }
})

注意: namespaced:true,要开启命名空间

3. 开启命名空间后,组件中读取state数据:

//方式一:自己直接读取
this.$store.state.personAbout.list

//方式二:借助mapState读取:
...mapState('countAbout',['sum','school','subject']),

4. 开启命名空间后,组件中读取getters数据:

//方式一:自己直接读取
this.$store.getters['personAbout/firstPersonName']

//方式二:借助mapGetters读取:
...mapGetters('countAbout',['bigSum'])

5. 开启命名空间后,组件中调用dispatch

//方式一:自己直接dispatch
this.$store.dispatch('personAbout/addPersonWang',person)

//方式二:借助mapActions:
...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

开启命名空间后,组件中调用commit

//方式一:自己直接commit
this.$store.commit('personAbout/ADD_PERSON',person)

//方式二:借助mapMutations:
...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),

例子:

Fenix:








总代码:

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入store
import store from './store'

//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	store,
	beforeCreate() {
		Vue.prototype.$bus = this
	}
})

App.js

<template>
	<div>
		<Count/>
		<hr>
		<Person/>
	</div>
</template>

<script>
	import Count from './components/Count'
	import Person from './components/Person'

	export default {
		name:'App',
		components:{Count,Person},
	}
</script>

store/index.js

//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
import countOptions from './count'
import personOptions from './person'
//应用Vuex插件
Vue.use(Vuex)

//创建并暴露store
export default new Vuex.Store({
	modules:{
		countAbout:countOptions,
		personAbout:personOptions
	}
})

store/count.js

//求和相关的配置
export default {
	namespaced:true,
	actions:{
		jiaOdd(context,value){
			console.log('actions中的jiaOdd被调用了')
			if(context.state.sum % 2){
				context.commit('JIA',value)
			}
		},
		jiaWait(context,value){
			console.log('actions中的jiaWait被调用了')
			setTimeout(()=>{
				context.commit('JIA',value)
			},500)
		}
	},
	mutations:{
		JIA(state,value){
			console.log('mutations中的JIA被调用了')
			state.sum += value
		},
		JIAN(state,value){
			console.log('mutations中的JIAN被调用了')
			state.sum -= value
		},
	},
	state:{
		sum:0, //当前的和
		school:'尚硅谷',
		subject:'前端',
	},
	getters:{
		bigSum(state){
			return state.sum*10
		}
	},
}

store/person.js

//人员管理相关的配置
import axios from 'axios'
import { nanoid } from 'nanoid'
export default {
	namespaced:true,
	actions:{
		addPersonWang(context,value){
			if(value.name.indexOf('王') === 0){
				context.commit('ADD_PERSON',value)
			}else{
				alert('添加的人必须姓王!')
			}
		},
		addPersonServer(context){
			axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
				response => {
					context.commit('ADD_PERSON',{id:nanoid(),name:response.data})
				},
				error => {
					alert(error.message)
				}
			)
		}
	},
	mutations:{
		ADD_PERSON(state,value){
			console.log('mutations中的ADD_PERSON被调用了')
			state.personList.unshift(value)
		}
	},
	state:{
		personList:[
			{id:'001',name:'张三'}
		]
	},
	getters:{
		firstPersonName(state){
			return state.personList[0].name
		}
	},
}

components/Count.vue

<template>
	<div>
		<h1>当前求和为:{{sum}}</h1>
		<h3>当前求和放大10倍为:{{bigSum}}</h3>
		<h3>我在{{school}},学习{{subject}}</h3>
		<h3 style="color:red">Person组件的总人数是:{{personList.length}}</h3>
		<select v-model.number="n">
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
		</select>
		<button @click="increment(n)">+</button>
		<button @click="decrement(n)">-</button>
		<button @click="incrementOdd(n)">当前求和为奇数再加</button>
		<button @click="incrementWait(n)">等一等再加</button>
	</div>
</template>

<script>
	import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
	export default {
		name:'Count',
		data() {
			return {
				n:1, //用户选择的数字
			}
		},
		computed:{
			//借助mapState生成计算属性,从state中读取数据。(数组写法)
			...mapState('countAbout',['sum','school','subject']),
			...mapState('personAbout',['personList']),
			//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)
			...mapGetters('countAbout',['bigSum'])
		},
		methods: {
			//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)
			...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
			//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)
			...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
		},
		mounted() {
			console.log(this.$store)
		},
	}
</script>

<style lang="css">
	button{
		margin-left: 5px;
	}
</style>

components/Person.vue

<template>
	<div>
		<h1>人员列表</h1>
		<h3 style="color:red">Count组件求和为:{{sum}}</h3>
		<h3>列表中第一个人的名字是:{{firstPersonName}}</h3>
		<input type="text" placeholder="请输入名字" v-model="name">
		<button @click="add">添加</button>
		<button @click="addWang">添加一个姓王的人</button>
		<button @click="addPersonServer">添加一个人,名字随机</button>
		<ul>
			<li v-for="p in personList" :key="p.id">{{p.name}}</li>
		</ul>
	</div>
</template>

<script>
	import {nanoid} from 'nanoid'
	export default {
		name:'Person',
		data() {
			return {
				name:''
			}
		},
		computed:{
			personList(){
				return this.$store.state.personAbout.personList
			},
			sum(){
				return this.$store.state.countAbout.sum
			},
			firstPersonName(){
				return this.$store.getters['personAbout/firstPersonName']
			}
		},
		methods: {
			add(){
				const personObj = {id:nanoid(),name:this.name}
				this.$store.commit('personAbout/ADD_PERSON',personObj)
				this.name = ''
			},
			addWang(){
				const personObj = {id:nanoid(),name:this.name}
				this.$store.dispatch('personAbout/addPersonWang',personObj)
				this.name = ''
			},
			addPersonServer(){
				this.$store.dispatch('personAbout/addPersonServer')
			}
		},
	}
</script>

到此这篇关于Vuex模块化和命名空间namespaced的文章就介绍到这了,更多相关Vuex模块化和命名空间内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 深入理解Vuex 模块化(module)

    一.为什么需要模块化 前面我们讲到的例子都在一个状态树里进行,当一个项目比较大时,所有的状态都集中在一起会得到一个比较大的对象,进而显得臃肿,难以维护.为了解决这个问题,Vuex允许我们将store分割成模块(module),每个module有自己的state,mutation,action,getter,甚至还可以往下嵌套模块,下面我们看一个典型的模块化例子 const moduleA = { state: {....}, mutations: {....}, actions: {....},

  • 浅谈vuex中store的命名空间

    为了防止store变的过于臃肿,我们可以为store注册模块,模块默认是属于全局命名空间的,也就是说当用下列代码分发action时,任意模块只要action中有addNews,就会得到执行 this.$store.dispatch('addNews') 有时候这种情况会不是我们想要的,为此我们可以为模块指定命名空间,相当于把它封装起来,这样在像上面那样分发action,具有命名空间的模块中的addNews函数就不会执行 当然你也可以指定位于特定的命名空间中的模块执行addNews这个函数,方法如

  • vuex命名空间的使用

    目录 Vuex由于使用单一状态树,应用的所有状态会集中到一个比较大的对象.当应用变得非常复杂时,store 对象就有可能变得相当臃肿. 因此,Vuex 允许我们将 store 分割成模块(module),每个模块拥有自己的 state.mutation.action.getter.甚至是嵌套子模块. 默认情况下,模块内部的 action.mutation 和 getter 是注册在全局命名空间的,这样使得多个模块能够对同一 mutation 或 action 作出响应.如果希望你的模块具有更高的

  • 详解Vuex下Store的模块化拆分实践

    前言 最近的项目用到了 vue.js + vuex + vue-router 全家桶,版本为 >2.0,在搞Store的时候发现,圈子里大部分关于vuex的文章都是比较基础的Demo搭建方式,很少有涉及到比较复杂的模块化拆分的Store实践,而且事实上也有朋友在实践中问到过这方面的内容,vuex自身提供了模块化的方式,因此在这里总结一下我自己在项目里的心得. 模块化拆分 vue.js的项目文件结构在这里就不说了,大家可以通过vue-cli初始化项目,脚手架会为你搭建一个start项目的最佳实践.

  • nuxt框架中对vuex进行模块化设置的实现方法

    1.Nuxt里怎么使用vuex? Nuxt.js 内置引用了 vuex 模块,所以不需要额外安装. Nuxt.js 会尝试找到应用根目录下的 store 目录,如果该目录存在,它将做以下的事情: 1.1> 引用 vuex 模块 1.2> 将 vuex 模块 加到 vendors 构建配置中去 1.3> 设置 Vue 根实例的 store 配置项 Nuxt.js 支持两种使用 store 的方式: 普通方式: store/index.js 返回一个 Vuex.Store 实例 模块方式:

  • 通过一个简单的例子学会vuex与模块化

    前言 Vuex 强调使用单一状态树,即在一个项目里只有一个 store,这个 store 集中管理了项目中所有的数据以及对数据的操作行为.但是这样带来的问题是 store 可能会非常臃肿庞大不易维护,所以就需要对状态树进行模块化的拆分. 这篇文章预设你已经了解vue相关的基础知识,因此本文不再赘述.需要学习的朋友可以参考这篇文章:http://www.jb51.net/article/110212.htm 对vuex的定位和解释可以看官方文档,说的很详细了,需要的朋友也可以通过这篇文章进行详细的

  • Vuex模块化和命名空间namespaced实例演示

    1. 目的: 让代码更好维护,让多种数据分类更加明确. 2. 修改store/index.js store/index.js const countAbout = { namespaced:true,//开启命名空间 state:{x:1}, mutations: { ... }, actions: { ... }, getters: { bigSum(state){ return state.sum * 10 } } } const personAbout = { namespaced:tru

  • Vuex模块化与持久化深入讲解

    目录 概述 Vuex的模块化 state数据状态对象 getters计算属性对象 actions异步请求对象 mutations数据同步对象 Vuex的使用方式 在自定义组件中使用 在自定义js文件中引用 Vuex持久化配置 main.js代码 modules/user.js代码 概述 Vuex作为VUE状态管理组件,能够将项目公共数据进行统一管理.而且可以按照不同的业务功能将数据状态分模块管理.另外,对于网页刷新导致Vuex状态丢失的问题可以使用vuex-persistedstate插件配置将

  • vuex操作state对象的实例代码

    Vuex是什么? VueX 是一个专门为 Vue.js 应用设计的状态管理架构,统一管理和维护各个vue组件的可变化状态(你可以理解成 vue 组件里的某些 data ). Vue有五个核心概念,state, getters, mutations, actions, modules. 总结 state => 基本数据 getters => 从基本数据派生的数据 mutations => 提交更改数据的方法,同步! actions => 像一个装饰器,包裹mutations,使之可以

  • Delphi实例演示Rect、Bounds生成TRect的区别

    本文以实例演示Rect.Bounds生成TRect的区别,实例代码如下: unitUnit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Button1: TButton; RadioGroup1: TRadioGroup; procedure Ra

  • Java查找 List 中的最大最小值实例演示

    以下实例演示了如何使用 Collections 类的 max() 和 min() 方法来获取List中最大最小值: /* author by w3cschool.cc Main.java */ import java.util.*; public class Main { public static void main(String[] args) { List list = Arrays.asList("one Two three Four five six one three Four&qu

  • Oracle RAC环境下的阻塞(blocking blocked)介绍和实例演示

    RAC环境下的阻塞不同于单实例情形,因为我们需要考虑到位于不同实例的session.也就是说之前查询的v$session,v$lock相应的应变化为全局范围来查找.本文提供了2个查询脚本,并给出实例演示那些session为阻塞者,哪些为被阻塞者.有关阻塞的概念以及单实例环境下的阻塞请参考:Oracle 阻塞(blocking blocked) 1.演示环境 scott@DEVDB> select * from v$version where rownum<2; BANNER ---------

  • C#各种数组的用法实例演示

    本文以实例演示了C#各种数组的基本用法.主要包括:一维数组.二维数组.锯齿型数组.长度不同的两个数组.3行4列的矩阵数组等. 具体实现代码如下: using System; class ArrayApp { public static void Main ( ) { //一维数组用法:计算数组中奇偶数的个数 Console.WriteLine("一维数组演示:一维数组中的奇偶数个数"); int[ ] arr1 = new int[ ] {8, 13, 36, 30, 9, 23, 4

  • jQuery数组处理详解(含实例演示)

    1. $.each(array, [callback]) 遍历[常用] 解释: 不同于例遍 jQuery 对象的 $().each() 方法,此方法可用于例遍任何对象(不仅仅是数组哦~). 回调函数拥有两个参数:第一个为对象的成员或数组的索引, 第二个为对应变量或内容. 如果需要退出 each 循环可使回调函数返回 false, 其它返回值将被忽略. each遍历,相信都不陌生,在平常的事件处理中,是for循环的变体,但比for循环强大.在数组中,它可以轻松的攻取数组索引及对应的值.例: 复制代

  • 关于Javascript模块化和命名空间管理的问题说明

    [关于模块化以及为什么要模块化] 先说说我们为什么要模块化吧.其实这还是和编码思想和代码管理的便利度相关(没有提及名字空间污染的问题是因为我相信已经考虑到模块化思想的编码者应该至少有了一套自己的命名法则,在中小型的站点中,名字空间污染的概率已经很小了,但也不代表不存在,后面会说这个问题). 其实模块化思想还是和面向对象的思想如出一辙,只不过可能我们口中所谓的"模块"是比所谓的"对象"更大的对象而已.我们把致力完成同一个目的的功能函数通过良好的封装组合起来,并且保证其

随机推荐