Uncaught TypeError: this.$store.commit is not a fu

2019-08-23 13:46发布

问题:

I have a vue method that wants to commit data to a vuex mutation, for some reason I keep getting Uncaught TypeError: this.$store.commit is not a function

The error triggers when I click the list item and call the function.


sample.vue

<li class="tabs-title" v-for="item in filteredItems" v-on:click="upComponents" :key="item.initials" >

export default {
  data() {
    return {
      search: null,
    };
  },
  computed: {
    filteredItems() {
      const coins = this.$store.state.coin.coin;
      if (!this.search) return coins;

      const searchValue = this.search.toLowerCase();
      const filter = coin => coin.initials.toLowerCase().includes(searchValue) ||
          coin.name.toLowerCase().includes(searchValue);

      return coins.filter(filter);
    },
  },

  methods: {
    upComponents(item) {
      this.$store.commit('updatedComp', item);
    },
  },

  mounted() {
    this.tabs = new Foundation.Tabs($('#exchange-tabs'), {
      matchHeight: false,
    });
  },
  destroyed() {
     this.tabs.destroy();
  },
};

This is the store.js file where I declare the mutation.

import Vue from 'vue';
import Vuex from 'vuex';
import coin from '../data/system.json';

Vue.use(Vuex);

export default {
  state: {
   coin,
   selectedCoin: 'jgjhg',
  },
  mutations: {
    updatedComp(state, newID) {
     state.selectedCoin.push(newID);
    },
  },
  getters: {
    coin: state => state.coin,
  },
};

main.js, this is where I declare the Vue app

import jQuery from 'jquery';
import Vue from 'vue';
import App from './App';
import router from './router';
import store from './store/store';


window.jQuery = jQuery;
window.$ = jQuery;

require('motion-ui');
require('what-input');
require('foundation-sites');


new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: { App },
});

This is the page I'm working on, where I load all the components:

<template>
  <div class="grid-container">
    <div class="grid-x">
      <div >
       <headline-exchange></headline-exchange>
       ...
      </div>
    </div>
  </div>
</template>



<script>
import Headline from './molecules/Headline';

export default {
  components: {
   'headline-exchange': Headline,
  },
};

</script>

回答1:

You are not creating a Vuex store. All you have is an object defining the store properties.

Change your store.js to be

export default new Vuex.Store({
  state: { ... },
  mutations: { ... }, 
  // etc
})

See https://vuex.vuejs.org/guide/#the-simplest-store