Vuex详解

VUEX是什么?
Vuex 是一个专为 Vue 开发的应用程序的状态管理模式,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

VUEX的优点
Vuex的状态存储是响应式的: 就是当你的组件使用到了这个 Vuex 的状态,一旦它改变了,所有关联的组件都会自动更新相对应的数据,这样开发者省事很多。

不能直接修改Vuex的状态: 如果是个全局对象变量,要修改很容易,但是在 Vuex 中不能这样做,想修改就得使用 Vuex 提供的唯一途径:显示地提交(commint)mutations来实现修改。这样做的好处就是方便我们跟踪每一个状态的变化,在开发过程中调试的时候,非常实用。

使用
1.安装:

npm install vuex --save

2.引用:

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

3.创建仓库Store

 const store = new Vuex.Store({});

Vuex的核心概念
state提供唯一的公共数据源,所有公共的数据都要放到store中的state中进行存储

const store = new Vuex.store({
	//state中存放的就是全局的数据
	state:{count:0}
})

组件中访问state的第一种方式

this.$store.state.数据名称

template中不需要this.
{{$store.state.count}}

组件中访问state的第二种方式(辅助函数)

//从vuex中按需导入mapState函数
import {mapState} from ”vuex“
//通过mapState函数将当前组件需要的全局数据,映射为当前组件的computed计算属性
computed:{
	...mapState(['count'])
}

直接写count
{{count}}

mutations同步传值


export default{
	 // payload:
	 //state :state对象
	setResturantName:(state,payload)=>{
		state.resturantName=payload.resturantName
	}
}

存值使用


onbut(){
    //参数:事件名 参数
	this.$store.commit('setResturantName',{
		resturantName:'aaa'
	})
}

Vuex异步加载(action.js)


export default{
	setResturantNameAsync:(centext,payload)=>{
		//centext等价于this.$store 代表了vue上下文
		setTimeout(() => {
			 //Action提交的是mutation
			centext.commit("setResturantName",payload);
		}, 3000)
	}
}

调用异步方法


onbutAsync(){
	this.$store.dispatch("setResturantNameAsync",{
		resturantName:'aaa'
	})
}

版权声明:本文为m0_71074684原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。