I am learning that vuex has made a small demo to add a price to totatlPrice by clicking a button in the sub-component, and then display it.
but the value that cannot be obtained from main.js mutations is obtained in main.js mutations. What should I do?
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: "-sharpapp",
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 and 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>