下载包:
npm install vuex --save
安装依赖
通常和main.js平级,创建store.js文件
import Vue from 'vue'
import Vuex from 'Vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
count:0,//全局默认的值
},
getters:{
},
mutations:{
}
})
组件中展示vuex的state数据:
展开运算符展示:
<template>
<div>
{{count}}
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
props: {
},
computed: {
...mapState(['count'])
}
}
</script>
<style scoped>
</style>
普通展示:
<template>
<div class="container">
<!-- 直接访问state的数据 -->
<span>{{$store.state.count}}</span>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
},
data() {
return {};
},
methods: {
}
};
</script>
用mutation变更state中的数据(集中监控数据的变化):
import Vue from 'vue'
import Vuex from 'Vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
count:0,//全局默认的值
},
getters:{
},
mutations:{
add(state){
state.count++
},
addN(state,step){
state.count += step
},
sub(state){
state.count--
},
subN(state,step){
state.count -= step
}
}
})
调用:
<template>
<div>
{{count}}
<button @click="btends1">加+1</button>
<button @click="btends2">加+n</button>
<button @click="btends3">减-1</button>
<button @click="btends4">减-N</button>
</div>
</template>
<script>
import {mapState,mapMutations} from 'vuex'
export default {
props: {
},
computed: {
...mapState(['count'])
},
methods:{
...mapMutations(['sub','subN']),
btends1(){
this.$store.commit('add')
},
btends2(){
this.$store.commit('addN',3)
},
btends3(){
this.sub()
},
btends4(){
this.subN(2)
}
}
}
</script>
<style scoped>
</style>