Vue mutations中获取state的值是未定义怎么办?

新手上路,请多包涵

我正在学习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>
阅读 3.3k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题