繁体   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