Vuex 状态管理

Vuex是一个专为Vue.js应用程序开发的状态管理模式,可支持众多组件使用其中的数据。store是Vuex的核心内容,其包含着应用中大部分的状态,如state、getters、mutations和actions等。

1.Vuex.state

Vuex.state是存放数据的地方,获取其中值有两种方式:

  1. 直接在页面中使用this.$store.state.name即可获取

  2. 通过引入方式进行获取:
    1.首先在组件中使用import 从vuex中引入状态
    javascript import { mapState,mapActions,mapMutations } from "vuex"
    2.在组件计算属性中注册引用所需要的属性

    computed:{
          ...mapState(['studentList','showModel'])
        }
    

    也可以在引用的时候进行改名:

    ...mapState({newName:state => state.name })
    

2.Vuex.getters

vue.getters类似于页面中的计算属性computed,是vuex的store.js中的设置项,可以对state属性进行进一步转化和处理并返回来,如:

getters:{							// 位置和state并列
	person (state) {				// 函数类型,作用与computed相似
		return `姓名:${state.name} 年龄:${state.age}`
	},
	newStudentList(state,getters){	// 需传递参数来引用state与自身已有属性
		return state.studentList.map(student => `${getters.person}`)
	}	 
}

引入方式和state一样可以使用$store.getters.person方式引入,也可以在组件中import引入然后在计算属性computed中使用…运算符注册声明,示例:

import { mapState, mapGetters } from "vuex";
export default {
	computed:{
		...mapState(['studentList']),
		...mapGetters(['person','newStudentList'])
	}
}

引入getterrs时对其进行改名处理:mapGetters( { newXXX : ‘xxx’ } ) - - - 不用像state一样必须使用函数才能改名

3.Vuex.mutations

修改state中的状态,一般只用来执行同步修改
使用方式:

mutations: {		
	changeStudentList(state, payload) { 
	//传参state和载荷:state获取要修改属性,载荷获取要修改成的内容
		state.studentList.push(payload)
	}
}

触发方式:

this.$store.commit('changeStudentList',tempObj)	//第一种方式
//第二种方式
import {mapState,mapMutations,mapActions} from 'vuex';	//引入state mutations actions
methods:{
	...mapActions(['getList','delStu']),	//state在computed中引入,mutations和actions在methods中引入
    ...mapMutations(['changeStudentList','setEditInfo']),
    handleClick(){
		this.changeStudentList(tempObj);	//执行mutations方法来修改state状态
		this.getList(1)		//使用actions方法来异步修改state状态
	}
}

4.Vuex.actions

提交mutation,让mutation去更改状态,通常用来执行异步
设置示例:

actions: {	
	changeStudentList({commit}, payload) {
		   //传递两个参数:执行期上下文(用于执行mutations方法,有多种方式)和载荷
		setTimeout(()=>{					 // 异步方式举例
			commit('changeStudentList',payload)	  // 在actions内执行mutations方法
		}, 1000)
	}
}

触发方式:

this.$store.dispatch('changeStudentList',tempObj)	//第一种方式,直接引用

第二种方式参见vuex.mutations中示例,其中有展示

5.Vuex.modules

vuex模块化:是建立在项目组件太多且每个组件都需要数据放置在vuex中,导致vuex中数据过多不好管理的情况下来进行分类分模块处理的一种方式,经过模块化处理之后每个vuex的module对应一个页面或组件的信息,使页面数据简洁化,方便操作及排错。
模块化操作步骤
1.新建store文件夹,把store.js放入文件夹中并改名为index.js
2.在main.js中,修改原vuex引入路径为更新后的index路径
3.在store文件夹内建立模块化文件,每个模块文件中都包含state、getters、mutations、actions
示例:

export default {
    namespaced:true,			//开启命名空间
    state:{
        book:'JavaScript语言精粹',
        price:'10'
    },
    getters:{
        coursePrice(state){ 
            return `¥${state.price}`
        }
    },
    mutations:{
        changePrice(state,{price}){
            state.price = price
        }
    },
    actions:{}
}

4 把模块化文件引入index文件当中

import student from './student'
import learn from './learn'
export default new Vuex.Store({
 	strict: process.env.NODE_ENV !== 'production', //开启严格模式,禁止在组件或页面中直接修改state状态
  	modules:{
    	student,
    	learn
  	}
})			// 至此(前四步),vuex部分设置全部完成,下面为引入方式

5 引入到页面或组件方式
未开启命名空间

  • 获取state : this.$store.state.moduleName.xxx
  • 获取getters: this.$store.getters.xxx
  • 获取mutations: this.$store.commit(‘xxx’)
  • 获取actions: this.$store.dispatch(‘xxx’)
  • 可以通过mapXXX 方式拿到getters、mutations、action,但是不能拿到state,如果想通过这种方式获取state,需要加命名空间:namespaced:true

开启命名空间

  • 获取state : this.$store.state.moduleName.xxx
  • 获取getters: this.$store.getters[‘moduleName/xxx’]
  • 获取mutations: this.$store.commit(‘moduleName/xxx’)
  • 获取actions: this.$store.dispatch(‘moduleName/xxx’)
  • 可以通过mapXXX: mapXXX(‘moduleName’, [‘xxx’]) mapXXX(‘moduleName’, {})

开启命名空间引入示例:

<script>
import { mapState,mapGetters,mapActions, mapMutations } from "vuex";
export default {
    data(){
        return {
            price:null
        }
    },
    computed:{
        ...mapState('learn',['courseName']),
        ...mapGetters('learn',['coursePrice'])
    },
    methods:{
        ...mapMutations('learn',['changePrice']),
        handleClick () {
            const price = this.price;
            this.changePrice({price:price})
        }
    }
}
</script>

关于vuex的严格模式
开启命令:

strict: process.env.NODE_ENV !== 'production'

Vuex传输为单向数据流,开启严格模式后,使用this.$store.state.price = 'XXX’方式修改state状态时就会出现报错

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值