You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 2中this.$store未定义错误排查与解决

Vue 2中TypeError: this.$store is undefined问题排查与解决

学习Vue 2教程时遇到TypeError: this.$store is undefined错误,编译无报错但浏览器控制台抛出该异常,此前查阅多个相关问题仍未明确原因,最终找到解决方法。

项目代码

App.vue

<template>
  <div id="app">
    <!-- <img alt="Vue logo" src="./assets/logo.png"> -->
    <!-- <HelloWorld msg="Welcome to Your Vue.js App"/> -->
    <TodoApp />
  </div>
</template>

<script>
// import HelloWorld from './components/HelloWorld.vue'
import TodoApp from './components/TodoApp.vue';

export default {
  name: 'App',
  components: {
    // HelloWorld,
    TodoApp
}
}
</script>
  body {
    font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
    line-height: 1.6;
    background: #e8f7f0;
  }
  .container {
    max-width: 1100px;
    margin: auto;
    overflow: auto;
    padding: 0 2rem;
  }
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Store (index.js)

import Vuex from 'vuex';
import Vue from 'vue';
import TodoModule from './modules/TodoModule.js';

// Load vuex
Vue.use(Vuex);

// Create store
export default new Vuex.Store({
    modules: {
        TodoModule
    }
});

Main.js

import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

TodoApp.vue

<template>
  <div>
    <h3>Vuex Todo App</h3>
    <div class="todos">
      <div class="todo" v-for="todo in allTodos" :key="todo.id">
        {{ todo.title }}
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  name: "TodoApp",
  computed: mapGetters(['allTodos'])
};
</script>

<style>

</style>

TodoModule.js

// import axios from "axios";

const state = {
    todos: [
        {
            id: 1,
            title: "first todo"
        },
        {
        id: 2,
        title: "second todo"
    },
    {
        id: 3,
        title: "third todo"
    }
]
};

const getters = {
    allTodos: state => state.todos
};

const actions = {};

const mutations = {};

export default {
    state,
    getters,
    actions,
    mutations
}

排查过程与解决方法

  • 尝试重启本地服务器、重启电脑,问题未解决,怀疑是Vue安装问题或依赖遗漏。
  • 最终定位根源:Vue与Vuex的npm包损坏或版本冲突。将Vue版本改为2.7.8、Vuex版本改为3.0.1,删除node_modules文件夹和package-lock.json文件后执行npm install,问题解决。

内容的提问来源于stack exchange,提问作者Zero Gear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 05:33:17