安装和使用
//npm install vuex --save
//src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
increment(state) {
state.count++
}
}
})
export default store
//main.js
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from './store'
new Vue({
render: (h) => h(App),
router,
store
}).$mount("#app");
正题
State 单一状态树
1、如何在Vue组件内获得Vuex的状态呢?
const Counter = {
template: `<div>{
{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。
2、mapState辅助函数摆脱每次将store里的状态声明为计算属性
当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性。
//组件内使用
import {
mapState } from 'vuex'
export defalut {
//...
computed: mapState({
** 三种方式 'count' 等同于 state => state.count **
count: state => state.count,
countStr: 'count',
countToUseThis(state) {
return state.count + this.localCount
}
})
}
当映射的计算属性名称和state的子节点名称一致时,可以直接给mapState传一个字符串数组
computed: mapState([
'count',
'count1'
...
])
3、mapState返回是一个对象,那组件自身使用的计算属性该怎么混搭使用呢?
mapState返回是一个对象,当我们组件内已经拥有了计算属性,该怎么办呢? 通常方法是将多个对象合并为一个,然后将最终值传个computed属性。 但是拥有 对象展开运算符 后, 使用就更为简单了。
computed:{
localCompued() {
},
...mapState({
** 三种方式 'count' 等同于 state => state.count **
count: state => state.count,
countStr: 'count',
countToUseThis(state) {
return state.count + this.localCount
})
}
Getter
1、Getter是啥?
有时候我们需要从 store 中的 state 中派生出一些状态&