Vuex
需要多个组件共享的组件状态可以通过Vuex进行管理
一、安装
npm install vuex --save
创建vuex实例
-
创建一个store的文件夹
-
创建一个index.js文件
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state:{ //保存状态 }, mutations: { //方法,通过该方法修改state数据,vuetools可以对修改状态进行跟踪和调试 increment(state){ state.count++ }, decrement(state){ state.count-- } }, actions: { //异步操作通过该方法 }, getters: { }, modules: { } }) export default store
在main.js中挂载
import Vue from 'vue' import App from './App' import router from './router' import store from './store/index' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, render: h => h(App) })
//使用 {{$store.state.counter}} //methods中使用mutations中的方法 methods: { add(){ this.$store.commit('increment') }, sub(){ this.$store.commit('decrement') } }
二、state数据修改
- 将修改数据的函数写进new Vuex.Store({})对象的mutations方法中
- 在需要修改数据的页面通过this.$store.commit()调用mutations中的函数
三、核心概念
-
State
- 放状态信息
- 单一状态树,所有需要管理的信息全部放到一个store中
-
Getters
- 类似于计算属性,用于数据经常变化的情况
- 两种写法
- getters函数不能通过普通方式传递参数,但是可以通过返回一个函数的方式,嵌套函数把参数传递进来
前端可通过$store.geters.moreAgeStu(18)的方式调用
getter可以通过mapGetters和计算属性合并
import {mapGetters} from 'vuex'
export default {
name: "CartNavBar",
data(){
return{
}
},
components:{
navBar,
},
computed:{
...mapGetters(['getCount'])//mapGetters前面必须有三个点
//magGetters还有一种写法:mapGetters({
// getCou: "getCount"
//})
},
mounted(){
}
}
- Mutation(响应式的)
提交同步函数
-
定义的函数包含两部分
-
事件类型(函数名)
-
回调函数(函数体)
回调函数可以传两个参数,第一个为state,第二个可以传递自定义参数或对象
-
写Mutation时,建议先建立一个mutations-type.js文件
//mutatison-types.js export const INSTATION = 'instation'
//mutation的写法 import {INSTATION} from 'mutation-types.js' mutations: { [INSTATION](state){ } }
//调用 import {INSTATION} from 'mutation-types.js' methods: { addition(){ this.$store.commit(INSTATION) } }
-
-
提交风格
this.$store.commit({ type: "事件类型", count,//该提交方式count就变成对象了,不在是单纯的数字 age: 18 })
-
响应规则
-
是在state中提前初始化好的数据
-
Vue.set()可以将没有加入响应系统的数据加入系统进行实时响应
-
Vue.deleat()实时响应删除
-
-
Action
-
在Mutation中进行异步操作,虽然页面会发生变化,但是devtooles工具中无法追踪到数据变化
actions:{ aUpdateInfo(context,payload){ setTimeout(() =>{ context.commit('updateInfo') }, 1000) }}
//调用updateInfo(){ this.$store.dispatch('aUpdateInfo', '我是payload')}
-
修改成功后给外边提示,可以再actions的异步函数封装成new Promise进行return,然后在updateInfo中进行使用,this.$store.dispatch(‘aUpdateInfo’, ‘我是payload’).then
-
提交异步函数
- Module
- 可以再modules中定义不同的模块,里面可以定义不同的state/Mutations/Actions/getters
- modules中的模块会被程序放到state中,调用时$store.state.模块名.属性名
- getter、mutations的调用不需要使用模块
- 可通过rootState,rootGetter拿到父模块的对应内容