vue结合webpack4使用vuex入门学习2

123 阅读2分钟

将上一个的练习代码拷贝一份,在这基础上继续学习

mutations中的方法名建议用一个变量来代替,这样可以减少发生错误的概率

在src下新建一个名为mutations-type.js的文件来放定义mutations方法名的变量,然后再在相应的文件引入

mutations-type.js

export const increment='increment'
export const remove='remove'

在main.js中引入

import {increment,remove} from './mutations-type.js'

并修改相应代码

在counter.vue的script标签中引入

import {increment,remove} from '../mutations-type.js'

且修改相应代码

modules的学习

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

在Vuex.Store中加入

modules:{
		a:{
			state:{
				name:'jing'
			},
			getters:{
				fullname1(state){
					return state.name+'2345'
				},
				fullname2(state,getters,rootState){
					return getters.fullname1+rootState.count
				}
			}
		}
	}

在amount.vue中调用

	<h4>{{$store.state.a.name}}</h4>
	<h4 style="color: red;">{{$store.getters.fullname2}}</h4>

运行结果

项目结构

Vuex 并不限制你的代码结构。但是,它规定了一些需要遵守的规则:

应用层级的状态应该集中到单个 store 对象中。

提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。

异步逻辑都应该封装到 action 里面。

只要你遵守以上规则,如何组织代码随你便。如果你的 store 文件太大,只需将 action、mutation 和 getter 分割到单独的文件。

对于大型应用,我们会希望把 Vuex 相关代码分割到模块中。下面是项目结构示例:

为了更方便的管理代码,我们将部分代码抽离到单个文件中,注意修改import的路径, 最终的目录结构如下

main.js

import Vue from 'vue'
import App from './App.vue'
import store from './store/index.js'
var vm=new Vue({
	el:'#app',
	data:{
	},
	render:function(createElements){
		return createElements(App)
	},
	store
})

index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

import mutations from './mutations.js'
import getters from './getters.js'
import moduleA from './modules/moduleA.js'

const state={
			count:0
		}
	var store=new Vuex.Store({
		// 如果组件想要访问state中的数据,只能通过this.$store.state.***来访问
		state,
		// 组件如果想要调用mutations,只能通过this.$store.commit("方法名")来调用
		mutations,
		// 如果store中的state中的数据在对外提供的时候需要做一层包装,推荐使用getters,
		// 组件通过this.$store.getters.***来调用getters中的函数
		getters,
		modules:{
			a:moduleA
		}
	})
export default store

getters.js


export default{
			open(state){
				return '当前的数量是'+state.count
			}
		}

mutations.js

import {increment} from './mutations-type.js'
export default{
			[increment](state){
				state.count++
			},
			// mutations的函数的参数列表中最多只能有两个参数,第一个是state,
			// 第二个是commit传递过来
			remove(state,num){
				state.count-=num
			}
		}

moduleA.js

 export default{
		state:{
			name:'jing'
		},
		getters:{
			fullname1(state){
				return state.name+'2345'
			},
			fullname2(state,getters,rootState){
				return getters.fullname1+rootState.count
			}
		}
	}

中文官网

个人网站:www.panbingwen.cn