vuex:count未在vue组件文件中定义

时间:2017-03-01 08:42:57

标签: javascript laravel-5.3 vuejs2 vuex

刚开始将vuex集成到我的laravel应用程序中,在官方vuex文档中使用示例计数器应用程序。

JS /组件/ calculate.vue

<template>
  <div>
    <p>{{ count }}</p>
    <p>
      <button @click="increment">+</button>
      <button @click="decrement">-</button>
    </p>
  </div>
</template>
<script >
  import store from '../app.js'

  export default {
    computed: {
      count () {

        return store.state.count
      }
    },
    methods: {
      increment () {
        store.commit('increment')
      },
      decrement () {
        store.commit('decrement')
      }
    }
  }
</script>

JS / app.js

const calculate = Vue.component('calculate', require('./components/calculate.vue'));

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment: state => state.count++,
    decrement: state => state.count--
  }
});



const app = new Vue({
  el: '#app'
});

使用webpack build

我在store.state.count行中return store.count未定义错误。

1 个答案:

答案 0 :(得分:0)

如果您要在app.js文件中创建商店,(因为您还没有提及),您需要添加

const calculate = Vue.component('calculate', require('./components/calculate.vue'));

Vue.use(Vuex) // this line

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment: state => state.count++,
    decrement: state => state.count--
  }
});

const app = new Vue({
  el: '#app'
});

不言而喻,您需要在此文件中导入Vuex

之后您需要修改,这部分代码:

const app = new Vue({
  el: '#app'
});

const app = new Vue({
  el: '#app',
  store // if you're vue-cli/babel else use store: store
});

js / components / calculate.vue

<template>
  <div>
    <p>{{ count }}</p>
    <p>
      <button @click="increment">+</button>
      <button @click="decrement">-</button>
    </p>
  </div>
</template>
<script >
 // import store from '../app.js' this import is not required

  export default {
    computed: {
      count () {
        return this.$store.state.count
      }
    },
    methods: {
      increment () {
        this.$store.commit('increment')
      },
      decrement () {
        this.$store.commit('decrement')
      }
    }
  }
</script>

导入不是必需的,因为store实例的每个组件都应该可以访问vue,要访问它,您只需要访问$store属性您组件中的vue实例为this (只要上下文不会通过回调或类似内容进行更改。)