Vuex modularization and namespaced example demonstration

Vuex modularization and namespaced example demonstration

1. Purpose:

Make the code easier to maintain and make the classification of various data clearer.

2. Modify store/index.js

store/index.js

const countAbout = {
  namespaced:true, //Open namespace state:{x:1},
  mutations: { ... },
  actions: { ... },
  getters: {
    bigSum(state){
       return state.sum * 10
    }
  }
}

const personAbout = {
  namespaced:true, //Open namespace state:{ ... },
  mutations: { ... },
  actions: { ... }
}

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

Note: namespaced:true, to enable namespace

3. After opening the namespace, read the state data in the component:

//Method 1: Read this.$store.state.personAbout.list directly


//Method 2: Read with mapState:
...mapState('countAbout',['sum','school','subject']),

4. After opening the namespace, read the getters data in the component:

//Method 1: Read this.$store.getters['personAbout/firstPersonName'] directly

//Method 2: Read with mapGetters:
...mapGetters('countAbout',['bigSum'])

5. After opening the namespace, call dispatch in the component

//Method 1: dispatch directly
this.$store.dispatch('personAbout/addPersonWang',person)


//Method 2: With mapActions:
...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

After opening the namespace, call commit in the component

//Method 1: commit directly
this.$store.commit('personAbout/ADD_PERSON',person)


//Method 2: With mapMutations:
...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),

example:

Fenix:

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

insert image description here
insert image description here
insert image description here
insert image description here

Total code:

insert image description here

main.js

//Introduce Vue
import Vue from 'vue'
//Introduce App
import App from './App.vue'
//Introduce store
import store from './store'

//Turn off Vue's production prompt Vue.config.productionTip = false

//Create 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

//This file is used to create the core store in Vuex
import Vue from 'vue'
//Introduce Vuex
import Vuex from 'vuex'
import countOptions from './count'
import personOptions from './person'
//Apply Vuex plug-in Vue.use(Vuex)

//Create and expose the store
export default new Vuex.Store({
	modules:{
		countAbout:countOptions,
		personAbout:personOptions
	}
})

store/count.js

//sum related configuration export default {
	namespaced:true,
	actions:{
		jiaOdd(context,value){
			console.log('jiaOdd in actions is called')
			if(context.state.sum % 2){
				context.commit('JIA',value)
			}
		},
		jiaWait(context,value){
			console.log('jiaWait in actions is called')
			setTimeout(()=>{
				context.commit('JIA',value)
			},500)
		}
	},
	mutations:
		JIA(state,value){
			console.log('JIA in mutations is called')
			state.sum += value
		},
		JIAN(state,value){
			console.log('JIAN in mutations is called')
			state.sum -= value
		},
	},
	state:{
		sum:0, //Current sum school:'Shang Silicon Valley',
		subject:'front end',
	},
	getters:{
		bigSum(state){
			return state.sum*10
		}
	},
}

store/person.js

//Personnel management related configuration 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('The person added must have the surname Wang!')
			}
		},
		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('ADD_PERSON in mutations is called')
			state.personList.unshift(value)
		}
	},
	state:{
		personList:[
			{id:'001',name:'张三'}
		]
	},
	getters:{
		firstPersonName(state){
			return state.personList[0].name
		}
	},
}

components/Count.vue

<template>
	<div>
		<h1>Current sum: {{sum}}</h1>
		<h3>The current sum is magnified 10 times: {{bigSum}}</h3>
		<h3>I am in {{school}}, studying {{subject}}</h3>
		<h3 style="color:red">The total number of people in the Person component is: {{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)">Add if the current sum is an odd number</button>
		<button @click="incrementWait(n)">Wait a while before adding</button>
	</div>
</template>

<script>
	import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
	export default {
		name:'Count',
		data() {
			return {
				n:1, //number selected by the user }
		},
		computed:{
			//Generate calculated properties with the help of mapState and read data from state. (Array writing)
			...mapState('countAbout',['sum','school','subject']),
			...mapState('personAbout',['personList']),
			//Generate calculated properties with the help of mapGetters and read data from getters. (Array writing)
			...mapGetters('countAbout',['bigSum'])
		},
		methods: {
			//Generate the corresponding method with the help of mapMutations, which will call commit to contact mutations (object writing)
			...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
			//Generate the corresponding method with the help of mapActions, which will call dispatch to contact actions (object writing)
			...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>Staff List</h1>
		<h3 style="color:red">The sum of the Count component is: {{sum}}</h3>
		<h3>The first person in the list has the name: {{firstPersonName}}</h3>
		<input type="text" placeholder="Please enter your name" v-model="name">
		<button @click="add">Add</button>
		<button @click="addWang">Add a person with the surname Wang</button>
		<button @click="addPersonServer">Add a person with a random name</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>

This is the end of this article about Vuex modularization and namespace namespaced. For more relevant Vuex modularization and namespace content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to implement modular settings of vuex in nuxt framework
  • Detailed explanation of the modular splitting practice of Store under Vuex
  • Learn vuex and modularity through a simple example
  • In-depth understanding of Vuex modularity (module)
  • Use of vuex namespace
  • A brief discussion on the namespace of store in vuex

<<:  Three ways to refresh iframe

>>:  Mysql database index interview questions (basic programmer skills)

Recommend

The implementation principle of Tomcat correcting the JDK native thread pool bug

To improve processing power and concurrency, Web ...

Detailed explanation of how to install PHP7 on Linux

How to install PHP7 on Linux? 1. Install dependen...

JavaScript flow control (loop)

Table of contents 1. for loop 2. Double for loop ...

Discussion on the browsing design method of web page content

<br />For an article on a content page, if t...

Solution to mysql login warning problem

1. Introduction When we log in to MySQL, we often...

Three implementation methods of Mysql copy table and grant analysis

How to quickly copy a table First, create a table...

mysql creates root users and ordinary users and modify and delete functions

Method 1: Use the SET PASSWORD command mysql -u r...

This article teaches you how to import CSS like JS modules

Table of contents Preface What are constructible ...

How familiar are you with pure HTML tags?

The following HTML tags basically include all exis...

Detailed explanation of DOM DIFF algorithm in react application

Table of contents Preface What is VirtualDOM? Rea...

How to use Linux tr command

01. Command Overview The tr command can replace, ...

A brief introduction to bionic design in Internet web design

When it comes to bionic design, many people will t...

MySQL intercepts the sql statement of the string function

1. left(name,4) intercepts the 4 characters on th...

How to set horizontal navigation structure in Html

This article shares with you two methods of setti...