我有幾個 Pinia 商店應該共享一組動作和吸氣劑,我不太確定如何有效地實作這一點。
我正在構建一個應用程式,讓用戶可以管理許多不同的媒體(書籍、電影、電視節目等)。我目前考慮的方式是為每種媒體型別創建一個商店,例如 BookStore、MovieStore 等。許多 getter 和操作(例如,count和deleteOne)在這些不同的商店之間完全相同。
我如何在這里實作 DRY?Pinia 檔案的示例主要集中在其他商店中重用動作和 getter,但我認為這并不能完全解決我完全繼承一組 getter 和 setter 的用例。
我在這里嘗試的繼承方法是反模式嗎?
uj5u.com熱心網友回復:
這是可以使用插件檔案實作的
示例電影:
對于每個州,您有多個使用共享命名方案的商店:
- item:單個物體item(單個電影詳情)
- collection: 專案的集合(所有電影的集合)
每個商店都將具有相同的 CRUD 操作,僅更改 URL
- getCollection:從 API 獲取專案串列并將回應設定為集合(https://url.com/movies)
- getItem:從 API 獲取單個專案并將回應設定為專案 ( https://url.com/movies/id )
- handleError:向用戶顯示帶有錯誤資訊的警報
創建插件:
function BaseStorePlugin () {
return {
collection: [],
item: {},
getCollection: function (url) {
api.get(url)
.then((response) => {
this.collection = response.data;
})
.catch((error) => {
this.handleError(error);
});
},
getItem: function (url) {
api.get(url)
.then((response) => {
this.item = response.data;
})
.catch((error) => {
this.handleError(error);
});
},
handleError: function (error) {
window.alert(error);
},
};
}
給 Pinia 提供插件:
const pinia = createPinia();
pinia.use(BaseStorePlugin);
示例 movieStore.js(使用共享操作和狀態)
import { defineStore } from 'pinia';
import { api } from 'src/boot/axios';
export const useMovieStore = defineStore({
id: 'movie',
state: () => ({
movieSpecificStateObject: {},
}),
actions: {
movieSpecificAction (url) {
console.log(this.item);
api.get(url)
.then((response) => {
// handle response
})
.catch((error) => {
this.handleError(error);
});
},
},
});
組件中的示例用法
<template>
<div
v-for="movie in movieStore.collection"
:key="movie.id"
>
<div>
{{ movie.name }}
</div>
</div>
</template>
<script setup>
import { onMounted } from 'vue';
import { useMovieStore } from 'src/stores/movieStore.js';
const movieStore = useMovieStore();
onMounted(() => {
movieStore.readCollection('http://url.com/movies');
});
</script>
編輯:1
如果您將背景關系傳遞到插件中,您可以訪問商店和傳遞給其中的選項,您可以從中檢查商店 ID,并且只回傳特定商店,如下所示
function BaseStorePlugin (context) {
const allowedStores = ['movie', 'album'];
if (allowedStores.includes(context.store.$id)) {
return {
collection: [],
getCollection: function () {
const fakeCollection = Array.from({length: 10}, () => Math.floor(Math.random() * 40));
fakeCollection.forEach((item) => {
this.collection.push({
id: item,
name: `name${item}`
});
});
},
};
};
}
我已經使用 3 家商店創建了一個非常基本的示例,上面的檢查可在此處的代碼框上找到
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/529568.html
標籤:Vue.js遗产松树
