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

Vue3 CDN项目中如何在main.js中访问分离的Vuex4 Store?

Vuex与main.js分离后store.state undefined问题解决

问题背景

项目结构

> public 
>   scripts
>     - cdn
>       - vue.js
>       - vuex.js
>     main.js
>     store.js
>     index.html

相关代码

index.html 脚本引入

<script src="./scripts/cdn/vue.js"></script>
<script src="./scripts/cdn/vuex.js"></script>
<script src="./scripts/main.js" type="module"></script>

index.html DOM结构

<div id="app"> <div v-for="item in items" >{{item.text}}</div> </div>

store.js 代码

console.log('test in store.js', store.state)
const store = new Vuex.createStore({
  state: {
    items: [{
      text: 'ahhh STORE 1'
    }, {
      text: 'ahhh STORE 2'
    }],
  },
  mutations: {},
  actions: {
    test({
      state
    }) {
      console.log(state.items)
    }
  },
  modules: {}
})

main.js 代码

import * as store from "./store.js";
const {
  onMounted,
  onUpdated,
  onUnmounted,
  ref,
  reactive,
  getCurrentInstance
} = Vue;
const App = {
  state: store,
  data() {
    return {};
  },
  methods: {},
  setup(props, context) {
    onMounted(() => {
      console.info("App mounted!");
      console.log('mounted state', store.state)
    });
    onUpdated(() => {
      console.info("App updated!");
    });
    onUnmounted(() => {
      console.info("App unmounted!");
    });
  }
};
const app = Vue.createApp(App);
app.use(store)
app.mount("#app");

问题现象

store.js中能正常打印Proxy { <target>: {…}, <handler>: {…} },但main.js的onMounted钩子中store.state返回undefined。将createStore逻辑移到main.js内可正常运行,但希望保持Store与main.js分离。


解决方案

问题根源

  1. store.js未导出store实例:创建的store常量没有通过export对外暴露,导致main.js导入后无法获取到实例。
  2. main.js导入和使用方式错误:import * as store会把模块导出的所有成员包裹在一个对象里,而app.use()需要的是Vuex store实例本身,不是这个包裹对象。另外,setup中访问store需要用Vuex提供的useStore钩子。

修改步骤

1. 修正store.js,导出store实例

// 先创建store实例
const store = new Vuex.createStore({
  state: {
    items: [{
      text: 'ahhh STORE 1'
    }, {
      text: 'ahhh STORE 2'
    }],
  },
  mutations: {},
  actions: {
    test({
      state
    }) {
      console.log(state.items)
    }
  },
  modules: {}
})
// 导出store实例
export default store;
// 移到创建之后再打印,避免变量未定义报错
console.log('test in store.js', store.state)

2. 修正main.js,正确导入并使用store

// 直接导入默认导出的store实例
import store from "./store.js";
const {
  onMounted,
  onUpdated,
  onUnmounted,
  ref,
  reactive,
  getCurrentInstance
} = Vue;
const App = {
  data() {
    return {};
  },
  // 模板要访问items,需要通过computed映射store的state
  computed: {
    items() {
      return this.$store.state.items;
    }
  },
  methods: {},
  setup(props, context) {
    // 在setup钩子中必须用Vuex.useStore()获取store实例
    const vuexStore = Vuex.useStore();
    onMounted(() => {
      console.info("App mounted!");
      console.log('mounted state', vuexStore.state)
    });
    onUpdated(() => {
      console.info("App updated!");
    });
    onUnmounted(() => {
      console.info("App unmounted!");
    });
  }
};
const app = Vue.createApp(App);
// 传入store实例给app.use()
app.use(store)
app.mount("#app");

额外说明

  • 原store.js开头的console.log会因变量提前引用报错,必须移到store实例创建之后。
  • 模板中的items需要通过组件的computed映射$store.state.items,或者直接在模板中写v-for="item in $store.state.items",否则模板无法找到该变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:10:31