1.组件共用Store修改state更新到组件
2.原理图
3.代码
import Vuex from 'Vuex'
Vue.use(Vuex)
let store = new Vuex.store({
state:{
totalPrice:0
},
getters:{
getTotal(state){
return state.totalTotal
}
},
mutations:{
increment (state,price) {
state.totalPrice +=price
},
decrement(state,price){
state.totalPrice -=price
}
},actions:{
increase(context,id) {
api(id,function(price){
context.commit('increment',this.price)
})
}
}
})
new Vue({
el:'#app',
store,
template:'<App/>',
compoents:{ App }
})
App模板中:
<template>
<div id="app">
<img src="./assets/logo.png">
{{ totalPrice }}
<apple></apple>
<banana></banana>
</div>
</template>
<script>
components:{App,Banana},
computed:{
totalPrice() {
//return this.$store.state.totalPrice
return this.$store.getters.getTotal
}
}
</script>
apple组件
<template>
<div class="hello">
<h1>{{msg}}</h1>
<button @click="addOne"> add one </button>
<button @click="minusOne"> minus one </button>
</div>
</template>
<script>
export default {
data () {
return {
msg:'i am apple',
price:5
},methods:{
addOne() {
this.$store.dispatch('increase',this.price)
},minusOne() {
this.$store.commit('minusOne',this.price)
}
}
}
}
</script>
4.参考文档
https://vuex.vuejs.org/zh-cn/intro.html
网友评论