用途
用于数据共享,组件之间的父子组件可以传递数据,但是没有关系的组件之间想要共享数据会很难,所以需要使用vuex来共享数据(状态),数据也叫状态
概念
state
数据存储
mutation
用于修改state中值,必须是通过他才可以修改state的值,使用this.$store.commit调用
action
异步修改state的值,也是通过调用mutation实现,使用$store.dispatch 调用
getter
修饰state中的值
安装
两种使用方式
- this.$store.state.count
- import {mapState} from vue,在computed中使用…mapState[‘count’]
store
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
num: 10
},
mutations: {
add(state) {
state.num++
},
addN(state, n) {
state.num += n
}
},
actions: {
add1(context) {
context.commit('add')
}
},
getters: {
show(state) {
return '我的数量是:' + state.num
}
},
modules: {}
})
使用一
<template>
<div>
<span>数量:{{$store.state.num}}</span><br/>
<button @click="add">+</button>
<button @click="addN(3)">N</button>
<br/>
<button @click="add1">异步+</button>
</div>
</template>
<script>
export default {
name: 'P1',
methods: {
add() {
this.$store.commit('add')
},
addN(n) {
this.$store.commit('addN', n)
},
add1() {
setTimeout(() => {
this.$store.dispatch('add1')
}, 1000)
}
}
}
</script>
<style scoped>
</style>
使用二
<template>
<div>
<span>数量:{{num}}</span><br/>
<span>{{show}}</span>
<br>
<button @click="increase">add</button>
</div>
</template>
<script>
import { mapGetters, mapState, mapMutations } from 'vuex'
export default {
name: 'P2',
computed: {
...mapGetters(['show']),
...mapState(['num'])
},
methods: {
...mapMutations({
add: 'add'
}),
increase() {
this.add()
}
}
}
</script>
<style scoped>
</style>