【发布时间】:2019-09-06 01:22:19
【问题描述】:
尝试在 Nuxt 和 typescript 中创建一个项目。但是文档很差,我遇到了很多问题。不知何故能够解决其中的大部分问题,但遇到了 商店 的问题。根据 Nuxt 文档,存储目录中的每个文件都被转换为一个模块。
为了更好地组织我的项目,我决定在 store 文件夹中添加一个子文件夹。但是,在此更改之后,我的组件在调用 Mutation、Action 和从存储/模块获取值时遇到问题。
当我在 Vue 选项卡 (Vuex) 中检查开发人员控制台时,我可以看到我的 State 和 getter 在模块之前有子文件夹名称。
如果我决定将每个新模块/存储放在 store 文件夹中,一切都会正常工作。
我正在为我的模块使用vuex-module-decorators 包,因为我认为它提高了代码的可读性并简化了流程。
我得到的错误是:
[vuex] unknown action type: applicationStage/initializeArticles
[vuex] unknown mutation type: applicationStage/addArticle
所以问题是:
- 我做错了吗?
- 我能否在 store 文件夹中有一个子文件夹,以及如何注册模块以在创建模块时跳过子文件夹名称?
我的商店文件夹结构
-store
--index.ts
--progress
---applicationStage.ts
./store/progress/applicationStage.ts
import {
Module,
Action,
VuexModule,
Mutation,
MutationAction
} from "vuex-module-decorators";
interface Article {
title: string;
body: string;
published: boolean;
meta: {
[key: string]: string;
};
}
const articles = [
{
title: "Hello World!",
body: "This is a sample article.",
published: true,
meta: {}
},
{
title: "My writing career continues!",
body: `...but I've run out of things to say.`,
published: false,
meta: {}
}
];
@Module({
name: "applicationStage",
stateFactory: true,
namespaced: true
})
export default class ApplicationStageModule extends VuexModule {
articles: Article[] = [
{
title: "Initial article",
body:
"This is the starting point, before we initialize the article store.",
published: true,
meta: {}
}
];
get allArticles() {
return this.articles;
}
get publishedArticles() {
return this.articles.filter(article => article.published);
}
@MutationAction({ mutate: ["articles"] })
async initializeArticles() {
return { articles };
}
@Mutation
addArticle() {
this.articles.push({
title: "Hello World 2!",
body: "This is a sample article 2.",
published: true,
meta: {}
});
}
}
./components/HelloWorld.vue
<template>
<div>
{{ message }}
<h2>Published articles</h2>
<article v-for="article in articleList" :key="article.title">
<h3 v-text="article.title"/>
<div v-text="article.body"/>
</article>
</div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { getModule } from "vuex-module-decorators";
import ApplicationStageModule from "../store/progress/applicationStage";
@Component
export default class HelloWorld extends Vue {
message: string = "Hello world !";
articleStore = getModule(ApplicationStageModule, this.$store);
articleList: any[] = [
{
title: "Initial article",
body:
"This is the starting point, before we initialize the article store.",
published: true,
meta: {}
}
];
mounted() {
this.articleStore.initializeArticles(); // ERROR LINE
this.articleStore.addArticle(); // ERROR LINE
this.updateArticles();
}
public updateArticles() {
this.articleList = this.articleStore.allArticles;
}
}
</script>
我创建了一个沙盒,可以在其中复制我的问题https://codesandbox.io/s/723xyzl60j
【问题讨论】:
-
你在一年前就问过这个问题,但你找到答案了吗?使用
namespace你会失去类型安全,这绝对不是我想要的......
标签: typescript vuex nuxt.js vuex-modules