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

在Laravel 8的Inertia技术栈(Vue3)中使用Vuex报错如何解决

问题原因与修复方案

核心错误点

  • 使用了适配Vue2的Vuex 3.x写法,Vue3对应Vuex 4.x的实例化、注册逻辑已变更
  • 代码执行顺序错误:提前导入并实例化Store后,才执行Vuex注册操作,触发了初始化顺序校验报错
  • 存在多余配置:Vue3中不需要将store作为根组件属性传入,也无需单独调用.use(Vuex)

修改后的代码

Store/index.js

// 改用Vuex 4提供的createStore方法创建实例
import { createStore } from 'vuex'

export const store = createStore({
    state () {
        return {
            count: 0
        }
    },
    mutations: {
        INCREMENT(state){
            state.count++
        },
        DECREMENT(state){
            state.count--
        }
    }
})

app.js

require('./bootstrap');

import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/inertia-vue3';
import { InertiaProgress } from '@inertiajs/progress';
// 无需单独导入Vuex,直接导入创建好的store即可
import { store } from './Store'

const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => require(`./Pages/${name}.vue`),
    setup({ el, app, props, plugin }) {
        return createApp({ render: () => h(app, props) })
            .use(plugin)
            // 注册store,自动完成Vuex初始化,无需额外调用.use(Vuex)
            .use(store)
            .mixin({ methods: { route } })
            .mount(el);
    },
});

InertiaProgress.init({ color: '#4B5563' });

修改后重新启动项目编译即可生效,可在组件内通过this.$store或者组合式API的useStore方法正常访问Vuex实例。

内容的提问来源于stack exchange,提问作者Jarliev Pérez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:21:03