簡體   English   中英

Vue 和 Pinia 的可重用組件

[英]Reusable components with Vue and Pinia

我想創建一個名為 Table 的可重用組件,它將使用另外兩個名為 Search 和 Records 的組件。 我還將創建一個 pinia 模塊,以使用 state 變量來提供輸入作為搜索鍵。 我將在搜索組件中設置該搜索鍵,然后我將按下記錄組件中的一個按鈕以根據該搜索鍵從后端獲取記錄。 現在,在 Records 組件中,我只在模板部分顯示該搜索變量。

就像我說的,我希望這個 Table 組件是可重用的。 例如,我要為訂單和客戶創建兩個表。 但是在這些情況下,當我鍵入任何內容以在 Orders 表中搜索輸入時,Customers 表也會顯示相同的搜索輸入。 有沒有辦法在不創建另一個模塊的情況下分離 pinia 模塊以使用此目的。 或者是否有任何適當的方法來實現該目標?

這是我的 Search.vue 組件:

<script setup lang="ts">
import { ref, watch } from "vue";
import { useTableStore } from "@/stores/table";

const store = useTableStore();
const search = ref<string>('');

watch(search, () => {
    store.setSearch(search.value);
});
</script>

<template>
    <input type="text" class="form-control" v-model="search">
</template>

<style scoped>

</style>

這是我的 Records.vue 組件:

<script setup lang="ts">
import { useTableStore } from "@/stores/table";

const store = useTableStore();
</script>

<template>
    {{  store.search }}
</template>

<style scoped>

</style>

這是我的 Table.vue 組件

<script setup lang="ts">
import Records from "@/components/table/Records.vue";
import Search from "@/components/table/Search.vue";
</script>

<template>
    <Search />
    <Records />
</template>

<style scoped>

</style>

這是我的 table.ts pinia 模塊:

import { ref } from "vue";
import { defineStore } from "pinia";

export const useTableStore = defineStore("table", () => {
    let search = ref<string>('');

    function setSearch(s: string) {
        search.value = s;
    }

    return {
        search,
        setSearch
    };
});

您應該將搜索值封裝在您的表組件中並從存儲中刪除該值。 你只是在那里不需要它。 然后你應該發出一個你從表的父級傳遞的事件(你知道你是用它來顯示客戶還是訂單)。 對於 99% 的情況,你不需要 pinia/vuex/global store。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM