Pinia ile depo oluşturmanın iki yolu vardır. Function/Setup yöntemini kullanıyorsanız $reset metodunun işlevini yerine getirmediğini fark etmiş olabilirsiniz.
<script setup> import { useStore } from './useStore' const store = useStore() store.$reset // 👈 </script>
🍍: Store "main" is build using the setup syntax and does not implement $reset().
Metodun Setup syntax ile çalışmasını sağlamak için bir Pinia eklentisi oluşturacağız ✨
Stores klasörünüz içerisinde plugins isimli bir klasör oluşturun ve içerisinde resetStore.js isimli bir dosya oluşturun.
Unutmadan projenize https://www.npmjs.com/package/lodash.clonedeep paketini eklediğinizden emin olun. lodash.clonedeep ile depo'nun başlangıç durumunu derinlemesine kopyalarız ve $reset fonksiyonunu ekleriz. Bu fonksiyon depo durumunu başlangıç değerine sıfırlar. Kopya kendisiyle ilişkili referansları kaldırmak için durumu tekrar derinlemesine kopyalamak önemlidir.
resetStore.js
import cloneDeep from 'lodash.clonedeep' export default function resetStore({ store }) { const initialState = cloneDeep(store.$state) store.$reset = () => store.$patch(cloneDeep(initialState)) }
Ardından main.js veya Pinia'yı başlattığınız herhangi bir yerde şunları yapın:
main.js
// ... import { resetStore } from './stores/resetStore' //... const pinia = createPinia() pinia.use(resetStore) app.use(pinia) //...
Örneğin ben bir projemde vitesse boilerplate kullanıyorum ve pinia src klasörü altındaki modules isimli bir klasörün içinde pinia.ts dosyası içerisinde oluşturuluyor.
src/modules/pinia.ts
import { createPinia } from 'pinia' import { type UserModule } from '~/types' ++ import storeReset from '~/store/plugins/storeReset' // Setup Pinia // https://pinia.vuejs.org/ export const install: UserModule = ({ isClient, initialState, app }) => { const pinia = createPinia() app.use(pinia) ++ pinia.use(storeReset) // Refer to // https://github.com/antfu/vite-ssg/blob/main/README.md#state-serialization // for other serialization strategies. if (isClient) pinia.state.value = (initialState.pinia) || {} else initialState.pinia = pinia.state.value }
bundan sonra storeName.$reset() metodu çalışacaktır.
Örnek kullanım
Kullanıcı sayfadan ayrıldığında store'u sıfırla.
~/src/pages/tonality.vue
onBeforeRouteLeave((to, from, next) => { console.log('onBeforeRouteLeave called') console.log('to: ', to) console.log('from: ', from) tonalityGuessingStore.$reset() next() })
Faydalanılan kaynaklar:
Top comments (0)