1.vuex是什么?
狀態(tài)管理模式臂痕,集中式存儲管理伯襟,多組件需要共享狀態(tài)時使用vuex
1.1狀態(tài)管理模式
單個組件中的狀態(tài)管理(單向數(shù)據(jù)流)
image.png
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `
<div>{{ count }}</div>
`,
// actions
methods: {
increment () {
this.count++
}
}
})
state,驅(qū)動應(yīng)用的數(shù)據(jù)源握童;
view姆怪,以聲明方式將 state 映射到視圖;
actions澡绩,響應(yīng)在 view 上的用戶輸入導(dǎo)致的狀態(tài)變化稽揭。
image.png
注意:Actions不是必須經(jīng)過的步驟
其中State可以通過Vue Components Commit(提交) Mutations修改(不經(jīng)過Actions),但是當(dāng)有異步操作時肥卡,Devtools無法跟蹤State的狀態(tài)溪掀,這時就需要經(jīng)過Actions
App.vue
<template>
<div id="app">
<h2>{{ $store.state.counter }}</h2>
<button @click="add">+</button>
<button @click="reduce">-</button>
</div>
</template>
<script>
export default {
name: 'App',
data() {},
methods: {
add() {
this.$store.commit('increment')
},
reduce() {
this.$store.commit('decrement')
}
}
}
</script>
store
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
counter: 100
},
mutations: {
increment(state) {
state.counter++
},
decrement(state) {
state.counter--
}
}
})
export default store
mapState
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
counter: 10
}
})
export default store
<template>
<div id="app">
<!-- <h2>{{$store.state.counter}}</h2> -->
<h2>{{ counter }}</h2>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'App',
data () {
return {}
},
computed:{
// 映射 this.counter 為 store.state.counter
...mapState(['counter'])
}
}
</script>
mapState使用對象的形式
<template>
<div id="app">
<h2>{{myCount}}</h2>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'App',
data () {
return {}
},
computed:{
// 映射 this.myCount 為 store.state.counter
...mapState({myCount:'counter'})
}
}
</script>