我正在学习vuex做了个小demo在子组件里面点击按钮 可以给 totatlPrice 加上一个价格,然后显示出来.
但是main.js mutations中获取获取不到state.totatlPrice的值.怎么办?
main.js:
import Vue from 'vue'
import App from './App'
import Vuex from 'vuex'
Vue.use(Vuex)
let store = new Vuex.Store({
state: {
totalPrice: 0
},
mutations: {
increment (state, price) {
alert(state.totatlPrice)
state.totatlPrice += price
},
decrement (state, price) {
state.totatlPrice -= price
}
}
});
Vue.config.productionTip = false;
/* eslint-disable no-new */
// router.beforeEach(router.push)
new Vue({
el: '#app',
store,
template: '<App/>',
components: {App}
});
App.vue:
<template>
<div id="app">
<img src="./assets/logo.png">
{{totalPrice}}
<apple></apple>
<banana></banana>
</div>
</template>
<script>
//import HelloWorld from './components/HelloWorld'
import Apple from './components/apple'
import Banana from './components/banana'
export default {
name: 'App',
components: {
Apple, Banana
},
computed:{
totalPrice (){
return this.$store.state.totalPrice
}
}
}
</script>
apple 和banana.vue:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<button @click="addOne">add one</button>
<button @click="minusOne">minus one</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'i am an apple',
price:5
}
},methods:{
addOne(){
// alert(1)
this.$store.commit('increment',this.price)
},
minusOne(){
this.$store.commit('decrement',this.price)
}
}
}
</script>