I want to create a reusable component called Table and it will use two other components called Search and Records. I'll also create a pinia module to use a state variable for giving an input as search key. I'll set that search key in Search component and then I'll press a button in Records component to get records from backend according to that search key. Right now, in Records component, I only display that search variable in template section.
Like I said, I want this Table component to be reusable. For example, I'm going to create two tables for Orders and Customers. But in these situation, when I type anything to search input in Orders table, also Customers table displays the same search input. Is there any way to seperate pinia module to use this purpose without creating another module. Or is there any proper approach to that goal?
This is my Search.vue component:
<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" v-model="search">
</template>
<style scoped>
</style>
This is my Records.vue component:
<script setup lang="ts">
import { useTableStore } from "@/stores/table";
const store = useTableStore();
</script>
<template>
{{ store.search }}
</template>
<style scoped>
</style>
This is my Table.vue component
<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>
And this is my table.ts pinia module:
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
};
});
CodePudding user response:
You should incapsulate search value in your Table component and remove this value from store. You just don't need it there. Then you should emit an event you pass from Table's parent (there you know if you are using it to display Customers or Orders). For 99% of cases you don't need pinia/vuex/global store.