Vuex用于状态的管理,当组件树很复杂时,底层的组件需要用到外层的组件变量,会比较麻烦,可以使用vuex作为一个全局的管理,需要的时候,获取和修改。能够做到实时响应界面的刷新。
多个组件:实现状态(变量)的共享,集中式管理,放到一处
首先安装vuex: npm install --save vuex
创建store.js,基本模块如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
// 状态
state: {
},
// 用于调用方法,到时可以使用devtool跟踪
mutations: {
},
// 计算属性
getters: {
},
// 异步的处理
actions: {
},
// 分模块
modules: {
}
})
实际例子:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
counter: 100
},
mutations: {
increase(state){
state.counter++
},
decrease(state){
state.counter--
},
increaseFive(state,count){
state.counter += count
}
},
getters: {
powerCount(state){
return state.counter * state.counter
},
powerCountAdd1(state,getter){
return getter.powerCount + 1
},
powerCountAddX(state){
return function (cnt) {
return cnt + state.counter
}
}
}
})
<template>
<div>
<h1>{{$store.state.counter}}</h1>
<button @click="incr">+</button>
<button @click="decr">-</button>
<button @click="incrFive(5)">+5</button>
<test1 :count="$store.state.counter"></test1>
<h1>====================================</h1>
<test1 :count="$store.getters.powerCount"></test1>
<test1 :count="$store.getters.powerCountAdd1"></test1>
<test1 :count="$store.getters.powerCountAddX(10)"></test1>
</div>
</template>
<script>
import Test1 from "./Test1";
export default {
name: "Test",
components:{
Test1
},
methods: {
incr() {
this.$store.commit('increase')
},
decr() {
this.$store.commit('decrease')
},
incrFive(cnt){
this.$store.commit('increaseFive',cnt)
}
}
}
</script>
<style scoped>
</style>
vuex,异步时,必须用actions
就是对mutatons包装一下,这样才能在devtools中跟踪到状态的变化,
可以通过promise来优化代码,通过返回promise对象的方式来后续使用函数链的方式