vuex(状态管理模式)

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。

  • 安装
    npm install vuex --save

  • 使用

  1. 初始化store/index.js
	import Vue from 'vue'
	import Vuex from 'vuex'
	Vue.use(Vuex)
	const store = new Vuex.Store({
    
      //创建VueX对象
    	state:{
    
    
        	name:'wangcai' //以键值对的形式存放需要进行管理的状态
    	}
	})

	export default store
  1. 将store挂载到当前项目的Vue实例(main.js)当中去
	import Vue from 'vue'
	import App from './App'
	import router from './router'
	import store from './store'
	
	Vue.config.productionTip = false
	
	new Vue({
    
    
  		el: '#app',
  		router,
  		store, 将创建的Vuex实例挂载到这个vue实例中
  		render: h => h(App)
	})

  • VueX中的核心内容

1.state 存放状态

2.mutations :操作state数据的方法的集合,比如对该数据的修改、增加、删除等等。

mutations方法都有默认的形参:([state] [,payload])
state是当前VueX对象中的state
payload是该方法在被调用时传递参数使用的

	this.$store.commit('edit',15)

3.getters :可以对state中的成员加工后传递给外界

Getters中的方法有两个默认参数
state 当前VueX对象中的状态对象
getters 当前getters对象,用于将getters下的其他getter拿来用

	this.$store.getters.methodName

4.actions 异步操作:由于直接在mutation方法中进行异步操作,将会引起数据失效。所以提供了Actions来专门进行异步操作,最终提交mutation方法。

Actions中的方法有两个默认参数
context 上下文(相当于箭头函数中的this)对象
payload 挂载参数

	this.$store.dispatch('methodName',{
    
    key:value})

5.modules :当状态非常多时,可以采用模块化管理模式。Vuex 允许我们将 store 分割成module。每个模块拥有自己的 state、mutation、action、getter。

扫描二维码关注公众号,回复: 14861020 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_41545048/article/details/108860021