【发布时间】:2020-03-02 06:59:39
【问题描述】:
我试图找到一种将 vuex 与可重用组件一起使用的方法,该组件将数据存储在商店中。问题是,我需要商店对于每个组件实例都是唯一的。
我认为文档的可重用模块是关键,但最后似乎不是为了这个目的,或者我不明白如何使用它。
父组件: (prop “req-path” 用于传递不同的 URL 以使每个 FileExplorer 组件提交从 API 获取数据的操作,具有该 url 路径)
<template>
<div class="container">
<FileExplorer req-path="/folder/subfolder"></FileExplorer>
<FileExplorer req-path="/anotherfolder"></FileExplorer>
</div>
</template>
<script>
import { mapState, mapGetters } from "vuex";
import FileExplorer from "@/components/FileExplorer.vue";
export default {
components: {
FileExplorer
}
};
</script>
可重用组件:
<template>
<div class="container">
<ul v-for="(item, index) in folderIndex" :key="index">
<li>Results: {{ item.name }}</li>
</ul>
</div>
</div>
</template>
<script>
import { mapState, mapGetters } from "vuex";
export default {
props: ["reqPath"],
},
computed: {
...mapState("fileExplorer", ["folderIndex"])
},
created() {
// FETCH DATA FROM API
this.$store
.dispatch("fileExplorer/indexingData", {
reqPath: this.reqPath
})
.catch(error => {
console.log("An error occurred:", error);
this.errors = error.response.data.data;
});
}
};
</script>
store.js 我在其中调用我在不同文件中分隔的商店模块,这里只有 fileExplorer 模块对我们感兴趣。 编辑:为了清楚起见,我简化了文件,但我还有一些其他状态和许多突变。
import Vue from 'vue'
import Vuex from 'vuex'
// Import modules
import { fileExplorer } from '@/store/modules/fileExplorer'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
fileExplorer,
…
}
})
@/store/modules/fileExplorer.js
import ApiService from "@/utils/ApiService"
export const fileExplorer = ({
namespaced: true,
state: {
folderIndex: {},
},
mutations: {
// Called from action (indexingData) to fetch folder/fil structure from API
SET_FOLDERS_INDEX(state, data) {
state.folderIndex = data.indexingData
},
actions: {
// Fetch data from API using req-path as url
indexingData({
commit
}, reqPath) {
return ApiService.indexingData(reqPath)
.then((response) => {
commit('SET_FOLDERS_INDEX', response.data);
})
.catch((error) => {
console.log('There was an error:', error.response);
});
}
}
});
我需要每个组件显示来自这 2 个不同 URL 的不同数据,而不是我在 2 个组件实例中获得相同的数据(不过这并不奇怪)。
非常感谢所有阅读所有内容的人!
【问题讨论】:
-
类似
folderIndex的声音不应存储在全局状态中,而应存储在每个FileExplorer组件的本地状态中。返回ApiService.indexingData(reqPath)并在created方法中处理响应,您可以将其添加到本地状态 -
对不起,我忘了提到我简化了我的商店模块文件,但我还有一些其他的状态和许多突变。如果只是为了获取数据,我确实会使用您的解决方案。
标签: vue.js vuejs2 vue-component vuex vuex-modules