【问题标题】:Uncaught TypeError: this.$store.commit is not a function未捕获的 TypeError:this.$store.commit 不是函数
【发布时间】:2018-03-07 01:27:49
【问题描述】:

我有一个 vue 方法想要将数据提交到 vuex 突变,由于某种原因,我不断收到 Uncaught TypeError: this.$store.commit is not a 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();
  },
};

这是我声明突变的 store.js 文件。

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,这是我声明 Vue 应用程序的地方

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 },
});

这是我正在处理的页面,我在其中加载所有组件:

<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>

【问题讨论】:

  • 您使用的是模块系统吗?如果是这样,您是否将Vuex 添加为插件,即Vue.use(Vuex)?见vuex.vuejs.org/en/installation.html
  • 在 store.js 中,是的。
  • 您是否将store 注入到根Vue 实例中,例如new Vue({ ..., store, ...})?见vuex.vuejs.org/en/…
  • 是的,我可以从商店中检索数据
  • 请添加更多代码!请在您的组件中添加完整代码。

标签: javascript vue.js vuejs2 vuex


【解决方案1】:

您没有创建Vuex 商店。您所拥有的只是一个定义商店属性的对象。

将您的 store.js 更改为

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

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

【讨论】:

  • 这正式解决了我问的问题,现在我得到了另一个类似的问题:) Uncaught TypeError: state.selectedCoin.push is not a function
  • @lopezi 很简单,selectedCoin 是字符串,不是数组
猜你喜欢
  • 1970-01-01
  • 2023-04-07
  • 2021-11-21
  • 2019-02-19
  • 2018-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多