LoginSignup
5

More than 5 years have passed since last update.

Vuexが使えない場合に 確認すべき初歩的な箇所

Posted at

結論

importするときのモジュール名は、大文字小文字のCaseを合わせよう。

検証環境

package.jsonをコピペしただけなので無駄なものマシマシ。

無駄なもの入っています!
{
  "dependencies": {
    "electron": "^1.6.8",
    "vue": "^2.3.3",
    "vue-loader": "^12.1.0",
    "vue-material": "^0.7.1",
    "vue-router": "^2.5.3",
    "vuex": "^2.3.1",
    "vuex-router-sync": "^4.1.2",
    "yarn": "^0.24.5"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-stage-2": "^6.24.1",
    "css-loader": "^0.28.4",
    "electron-packager": "^8.7.0",
    "style-loader": "^0.18.1",
    "vue-template-compiler": "^2.3.3",
    "webpack": "^2.6.0"
  }
}

症状

弄りすぎてどのときにどの症状、とは記録していないのですが、

  • コンポーネントからstoreが参照できない
    • this.$store
    • 結果、コンポーネント自体が表示できなかったりする
  • コンポーネントからVuexstore?のプロパティが参照できない
    • ...mapGettersを使うとgettersプロパティが無いと言われる
  • コンポーネントもstateも表示されるが、stateの変更が反映されず、再描画時にしか更新されない(これは特殊かも)

コード

かなり簡略化したもの

main.js

import Vue from 'vue';
import store from './store.js';
new Vue({
  store,
});

store.js

import Vue from 'Vue';
import Vuex from 'Vuex';
Vue.use(Vuex);

// 各オブジェクト定義

export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters,
});

test.vue

<template>
<div id="app">
  <p>{{ hoge}}</p>
  <p>
    <button @click="huga">huga</button>
  </p>
</div>
</template>

<script>

import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  computed: {
    ...mapGetters(['hoge']),
  },
  methods: {
    ...mapActions(['huga']),
  }
}
</script>

原因

import Vue from 'vue';
import Vue from 'Vue';

同一パッケージを別々に読み込むときのこの表記ゆれ。
どちらかに合わすこと。

Webpackに起因するものかは不明。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5