这个问题很烦我,我是Vue的新手,我正在尝试制作一个简单的应用程序来练习 .
现在我正在使用Vuex和Vue Router,这里是代码:
路由文件非常简单,只是非家庭路由的延迟加载 .
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/tracks',
name: 'tracks',
component: () => import(/* webpackChunkName: "about" */ './views/Tracks.vue')
}
]
})
视图组件,它只渲染视图子项:
<template>
<div id="tracks">
<logo></logo>
<search></search>
<songs></songs>
</div>
</template>
<script>
import Logo from '@/components/Logo.vue'
import Search from '@/components/Search.vue'
import Songs from '@/components/Songs.vue'
export default {
name: 'tracks',
components: { Logo, Search, Songs }
}
</script>
歌曲组件,这是我制作逻辑的容器(现在就列出的东西)
<template>
<section id="track-list" class="columns is-centered">
<div class="column is-4" v-show="!songList.length">
<div class="notification is-danger">
No tracks loaded :(
</div>
</div>
</section>
</template>
<script>
import { mapState } from 'vuex'
import SongCard from './SongCard.vue'
export default {
name: 'songs',
components: { SongCard },
computed: {
...mapState([ 'songs' ])
}
}
</script>
我认为问题出现在渲染周期中,组件已挂载,数据尚未加载,但这不是异步数据(至少不是我的),而是在状态下硬编码,初始化为空数组:
const state = {
songList: [ ],
song: null
}
// actions
const actions = {
}
// mutations
const mutations = {
// [tracks.GET_TOP](state, payload) {},
// [tracks.GET_TRACK](state, payload) {}
}
export default {
namespaced: true,
state,
actions,
mutations
}
由于我使用Vuex,我不使用 data() {}
键,否则我使用 computed
...我能在这做什么?我迷路了 .
Edit, here is the complete store file:
import Vue from 'vue'
import Vuex from 'vuex'
import artists from './modules/artists'
import songs from './modules/songs'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
artists,
songs,
countries: {
state: {
selected: 'Mexico',
list: [
{ value: 'spain', name: 'España' },
{ value: 'mexico', name: 'México' },
{ value: 'argentina', name: 'Argentina' }
]
}
}
},
actions,
mutations
})
1 回答
这里的主要问题是
songs
不是状态,它是一个命名空间模块,所以它不能像...mapState(['songs'])
那样直接访问 .要映射商店的
songs
模块的状态,我们使用mapState
帮助语法,用于命名空间模块:所以,关于这个问题的正确语法是:
请注意,您也可以像上面的示例一样传递对象而不是数组 .
有关更多信息,请参阅this .