如何在Vue中获取Vuex存储的JSON数据并在首页挂载后渲染展示
解决方案
先修正现有Vuex代码的问题
你当前的action写法存在嵌套数组的错误:JSON返回的responseData本身就是待办数组,你将它push到空数组后提交,会导致state.todos最终是[[{id:1,...}, {id:2,...}]]的嵌套结构,无法正常遍历渲染。修正后的action代码如下:
async getTodos (context) { const response = await fetch('../../data/todos.json') const responseData = await response.json() // 直接提交返回的原始数组即可 context.commit('getTodos', responseData) }
mutations和state的代码无需改动。
首页组件调用与渲染
根据你用的API风格选择对应写法即可:
1. 选项式API(兼容Vue2/Vue3)
<template> <div> <h2>待办列表</h2> <!-- 遍历渲染todo --> <div v-for="todo in todos" :key="todo.id" style="margin: 10px 0; padding: 10px; border: 1px solid #eee;"> <h3>{{ todo.title }}</h3> <p>描述:{{ todo.description }}</p> <p>截止时间:{{ todo.dueTo }}</p> </div> </div> </template> <script> // 导入mapState辅助函数,也可以不用直接手动写计算属性 import { mapState } from 'vuex' export default { computed: { // 将vuex的todos映射为当前组件的计算属性 ...mapState(['todos']) // 不用辅助函数的写法: // todos() { // return this.$store.state.todos // } }, // 组件挂载完成后触发拉取数据的action mounted() { this.$store.dispatch('getTodos') } } </script>
2. Vue3 组合式API(setup写法)
<template> <!-- 模板和选项式API完全一致 --> <div> <h2>待办列表</h2> <div v-for="todo in todos" :key="todo.id" style="margin: 10px 0; padding: 10px; border: 1px solid #eee;"> <h3>{{ todo.title }}</h3> <p>描述:{{ todo.description }}</p> <p>截止时间:{{ todo.dueTo }}</p> </div> </div> </template> <script setup> import { useStore } from 'vuex' import { onMounted, computed } from 'vue' const store = useStore() // 读取vuex中的todos状态 const todos = computed(() => store.state.todos) // 组件挂载后触发数据拉取 onMounted(() => { store.dispatch('getTodos') }) </script>
内容的提问来源于stack exchange,提问作者kozdro
相关产品推荐
相关产品推荐

