Cod*_*rts 1 vue.js vuex nuxt.js
我正在尝试使用 vuex 的帮助程序将操作映射到组件mapActions。这是我的 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
}
Run Code Online (Sandbox Code Playgroud)
这是我的组件 _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>
Run Code Online (Sandbox Code Playgroud)
然而,在created()生命周期挂钩内this.fetchLabel(this.$route.params.slug),它会在控制台中抛出以下错误:
[vuex] 未知操作类型:FETCH_LABEL
我错过了什么或做错了什么?请帮我解决这个问题。
请注意,在 Nuxt.js 中:
模块:商店目录中的每个 .js文件都被转换为命名空间模块(索引是根模块)。
您正在使用:
这是我的 labels.js vuex 模块:
如上所述使用 labels.js,因此您需要将所有内容作为命名空间模块进行访问,因此您的 mapAction 帮助程序应该如下所示:
methods: {
...mapActions({
nameOfMethod: 'namespace/actionName'
})
}
Run Code Online (Sandbox Code Playgroud)
所以你会得到这个:
...mapActions({
fetchLabel: 'labels/fetchLabel'
})
Run Code Online (Sandbox Code Playgroud)
当您希望保留操作名称作为方法名称时,您也可以通过这样做来清理它。
...mapActions('namespace', ['actionName']),
...
Run Code Online (Sandbox Code Playgroud)
所以你会得到这个:
...mapActions('labels', ['fetchLabel']),
...
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,计算出的 prop 都应该可以正常工作。
| 归档时间: |
|
| 查看次数: |
7928 次 |
| 最近记录: |