Vue3使用Vuex报错store is not a function且页面无内容如何解决?
问题排查与修复方案
1. 首要错误:Store导出导入不匹配
你在./store/index.ts中是命名导出export const store = createStore(...),但在main.ts里用的是默认导入import store from "./store",导致导入的store不是你创建的实例,触发store is not a function错误。
修复:
修改./store/index.ts最后一行,改成默认导出:
export default store
同时可以删掉./store/index.ts中无用的import { createApp } from 'vue'导入语句。
2. Store状态操作逻辑错误
2.1 Mutation赋值错误
你在mutation里写的是state.data = feedList,但初始化的state里不存在data字段,只有feedList字段。
修复:修改mutation逻辑:
mutations: { setFeedList(state:any, feedList:any) { state.feedList = feedList } }
2.2 Action请求取值错误
axios返回的响应对象中,实际接口数据存储在data属性下,你直接把整个响应对象提交给mutation会导致存储的数据结构不符合预期。
修复:修改action逻辑:
actions: { getPosts( { commit } ) { axios.get('http://localhost:3001/api/feed') .then(res => { commit('setFeedList', res.data) }) } }
3. Feed.vue逻辑错误
3.1 状态路径错误
你在computed中取的是store.state.data.feedList,但state下没有data层级,直接取store.state.feedList即可。
3.2 未触发Action拉取数据
你没有调用getPosts action,所以feedList永远是空数组,不会渲染数据。
3.3 v-for key值不规范
你直接用thePost作为v-for的key值,如果thePost是对象类型会触发警告,建议用接口返回的唯一标识作为key。
修复后的Feed.vue对应代码:
<template> <!-- 其他代码不变 --> <div id="testlist" v-for="thePost in feedList" :key="thePost.id"> {{ thePost }} </div> <!-- 其他代码不变 --> </template> <script lang="ts"> // 其他导入不变 export default { // 其他配置不变 setup () { const store = useStore(); // 触发action拉取数据 store.dispatch('getPosts') // 正确读取state const feedList = computed(() => store.state.feedList); console.log("feedList > ", feedList.value); return { feedList } }, } </script>
内容的提问来源于stack exchange,提问作者RoosDev
相关产品推荐
相关产品推荐

