如何通过Vuex模块向Vue组件传值?数据无法渲染至表格求助
Hey there, let's figure out why your roles data isn't showing up in the template even though you can see it in the console and Vuex DevTools. I spotted a couple of key issues in your code:
1. Template Syntax Errors
First, your template has a few syntax mistakes that will prevent Vue from rendering content correctly:
- You wrote
<di>instead of<div>(typo in the tag name) - The
v-fordirective has incorrect syntax: you used a colon:beforekeyinstead of a comma,, and the<p>tag isn't closed.
Fixed Template
<template> <div> <p v-for="(role, index) in roles" :key="index">{{ role.name }}</p> <!-- Replace role.name with the actual property you want to display from your role object --> </div> </template>
2. Vuex Module State Mapping
Since you're using a Vuex module (role), the roles state lives inside the module, not the root state. Your current mapState call is looking for roles in the empty root state, so it can't access the module's state.
Option 1: Use Namespaced Modules (Recommended)
First, enable namespacing in your role.js module (it's commented out right now):
// role.js export default { namespaced: true, // Uncomment this line state: { roles: [] }, getters: { roles (state) { return state.roles } }, mutations: { SET_ROLES (state, roles) { state.roles = roles } }, actions: { loadRoles ({ commit }) { return Axios.get('/settings/roles') .then((response) => { console.log(response.data) commit('SET_ROLES', response.data.roles) }) } } }
Then update the mapState in your component to target the role module:
<script> import { mapState } from 'vuex' export default { name: 'Role', metaInfo: { title: 'Role' }, created () { this.$store.dispatch('role/loadRoles') // Add module prefix since it's namespaced .then(() => { console.log('Roles loaded successfully') }) }, computed: { ...mapState('role', ['roles']) // Specify the module name here } } </script>
Option 2: Keep Non-Namespaced Module
If you don't want to use namespacing, you can access the module's state via the module name in the root state:
<script> import { mapState } from 'vuex' export default { // ... other options computed: { ...mapState({ roles: state => state.role.roles // Access role module's state directly }) } } </script>
3. Ensure Action Returns a Promise (Optional but Clean)
Your loadRoles action doesn't return a Promise right now, so the then in your component's created hook resolves to undefined. To fix this, return the Axios call:
// role.js actions loadRoles ({ commit }) { return Axios.get('/settings/roles') // Return the Promise .then((response) => { console.log(response.data) commit('SET_ROLES', response.data.roles) return response.data.roles // Optional: return data if you need it in the component }) }
After fixing these issues, your roles should render correctly in the template. Let me know if you still run into problems!
内容的提问来源于stack exchange,提问作者livreson ltc

