1.vuex是什么?
状态管理模式,集中式存储管理,多组件需要共享状态时使用vuex
1.1状态管理模式
单个组件中的状态管理(单向数据流)
image.png
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `
<div>{{ count }}</div>
`,
// actions
methods: {
increment () {
this.count++
}
}
})
state,驱动应用的数据源;
view,以声明方式将 state 映射到视图;
actions,响应在 view 上的用户输入导致的状态变化。
image.png
注意:Actions不是必须经过的步骤
其中State可以通过Vue Components Commit(提交) Mutations修改(不经过Actions),但是当有异步操作时,Devtools无法跟踪State的状态,这时就需要经过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>