counter/state.js
export default{
arr:[11,22,33]
}
counter/getter.js
export default{
sum(state){
return state.arr.reduce((a,b)=>a+b)
}
}
counter/mutations.js
export default{
inc(state,p){
state.arr.splice(p,1,++state.arr[p])//这样数据和视图都会更新
//state.arr[p]++ //这样数据会更新,视图不会更新
}
}
counter/index.js
import state from './state'
import getters from './getters'
import mutations from './mutations'
export default{
state,
getters,
mutations
}
components/counter.vue
<template>
<div id="class">
{{n}}<button @click='inc'>+</button>
</div>
</template>
<script>
export default{
props:["idx"],
data(){
return{
n:this.$store.state.Counter.arr[this.idx]
}
},
methods:{
inc(){
this.$store.commit("inc",this.idx)
this.n=this.$store.state.Counter.arr[this.idx]
}
}
}
</script>
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import Counter from './counter'
import List from './list'
Vue.use(Vuex)
var store = new Vuex.Store({
modules:{
Counter,
List
}
})
export default store
App.vue
<template>
<div id="app">
<Counter :idx="0"/>
<Counter :idx="1"/>
<Counter :idx="2"/>
{{sum}}
<List/>
<router-view/>
</div>
</template>
<script>
import Counter from './components/counter'
import List from './components/list'
export default {
name: 'App',
components:{
Counter,
List
},
computed:{
sum(){
return this.$store.getters.sum
}
}
}
</script>