Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
简介
每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
Vuex 和单纯的全局对象有以下两点不同:
- Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新
- 不能直接改变 store 中的状态,必须通过调用Vuex中的mutation中定义的方法,来改变其中定义的状态(state),这样我们就可以知道每一次状态的改变
其存在的意义是为了做到Vue中的所有组件互通数据
使用环境
如果我们在vue中的多个组件中使用了一个相同的变量,且一个组件中的变量改变其它的组件中的变量也需要改变 这个时候 我们就可以使用Vuex来存储这个变量
Vuex的五大核心
state:存储store的各种状态
mutation: 改变store的状态只能通过mutation方法
action: 异步操作方法
module: 模块化
getter: 相当于计算属性,过滤出来一些值
state的使用
Vuex的使用
- 存放及提取
const store = new Vuex.Store({
//存放状态信息
state: {
counter:1000,
},
}
//拿到counter的值
<h2>{{$store.state.counter}}</h2>
- 同步修改
mutations: {
//方法,改state提交mutation
//mutation响应规则
//mutation无法进行异步更新
increment(state) {
state.counter++
},
}
//在方法中提交mutation
methods: {
addition(){
//提交store的信息
this.$store.commit('increment')
}
}
- 异步修改
const store = new Vuex.Store({
//存放状态信息
state: {
Info: {
name : 'kobe',
age:20,
height : 1.98
}
},
mutations: {
increment(state) {
state.counter++
},
}
actions:{
//进行异步操作
//context上下文
//异步可以用setTimeout
aupdateInfo(context){
setTimeout(() =>{
context.commit('updateInfo')
},1000)
}
}
methods: {
updateInfo() {
// this.$store.commit('updateInfo')
// dispatch:含有异步操作,例如向后台提交数据,写法:this.$store.dispatch('action方法名',值)
//commit:同步操作,写法:this.$store.commit('mutations方法名',值)
this.$store.dispatch('aupdateInfo')
},
}
}
- 实际上 我们只是使用dispatch又调用了一次mutations中定义好的方法而已
- module的使用
// 在大量使用Vuex时为了避免代码过于臃肿 为了方便后期维护和避免命名冲突
// 在modules中划分,让每一个分离出去的State都有自己的getters,mutations,actions等
modules :{
a:modulesA
}
const modulesA = {
state : {
name : 'zhangsan'
}
mutation: {},
getter: {}
}
Vuex安装及配置
- 安装Vuex
npm i vuex --save
- 引用Vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
- 创建仓库Store
//创建一个 store
const store = new Vuex.Store({});
或
我们在创建Vue脚手架时选中Vuex 使其自带Vuex模板