我正在尝试使用来自 vuex 的 mapActions
助手将一个 Action 映射到一个组件。这是我的 labels.js vuex 模块:
export const FETCH_LABELS = 'FETCH_LABELS'
export const FETCH_LABEL = 'FETCH_LABEL'
const state = () => ({
labels: [
{ name: 'Mord Records', slug: 'mord', image: '/images/labels/mord.jpg'},
{ name: 'Subsist Records', slug: 'subsist', image: '/images/labels/subsist.jpg'},
{ name: 'Drumcode Records', slug: 'drumcode', image: '/images/labels/drumcode.png'},
],
label: {} // null
})
const mutations = {
FETCH_LABEL: (state, { label }) => {
state.label = label
},
}
const actions = {
fetchLabel({commit}, slug) {
let label = state.labels.filter((slug, index) => {
return slug == state.labels[index]
})
commit(FETCH_LABEL, { label })
},
}
const getters = {
labels: state => {
return state.labels
},
label: (state, slug) => {
}
}
export default {
state,
mutations,
actions,
getters
}
这是我的组件 _slug.vue 页面,我想在其中映射 fetchLabel 操作:
<template>
<div class="container">
<div class="section">
<div class="box">
<h1>{{ $route.params.slug }}</h1>
</div>
</div>
</div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
data() {
return {
title: this.$route.params.slug
};
},
computed: {
// Research
// labels() {
// return this.$store
// }
...mapGetters({
labels: "modules/labels/labels"
})
},
components: {},
methods: {
...mapActions({
fetchLabel: 'FETCH_LABEL' // map `this.add()` to `this.$store.dispatch('increment')`
})
},
created() {
console.log('created')
this.fetchLabel(this.$route.params.slug)
},
head() {
return {
title: this.title
}
},
layout: "app",
}
</script>
<style>
</style>
但是在 created()
生命周期 Hook 中 this.fetchLabel(this.$route.params.slug)
它会在控制台中抛出以下错误:
[vuex] unknown action type: FETCH_LABEL
我错过了什么或做错了什么?请帮我解决这个问题。
最佳答案
注意在 Nuxt.js 中:
模块:存储目录中的每个 .js 文件都被转换为命名空间模块(索引是根模块)。
您正在使用:
Here is my labels.js vuex module:
使用 labels.js 如上所述,因此您需要将所有内容作为命名空间模块进行访问,因此您的 mapAction 助手应该像这样:
methods: {
...mapActions({
nameOfMethod: 'namespace/actionName'
})
}
所以你会有这个:
...mapActions({
fetchLabel: 'labels/fetchLabel'
})
当您希望将操作名称保留为方法名称时,您也可以通过这样做来清理它。
...mapActions('namespace', ['actionName']),
...
所以你会有这个:
...mapActions('labels', ['fetchLabel']),
...
在这两种情况下,计算的 prop 都应该可以正常工作。
关于vue.js - Nuxt.js/Vuex - 在 mapActions 助手中使用命名空间模块,[vuex] 未知操作类型 : FETCH_LABEL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51838542/