Pinia:機能/セットアップ構文で作成された店舗のリセット方法
8562 ワード
ピアニアとは
PIIAはVue 3の状態管理ソリューションです.
あなたは“ああ、別のツールを考えている?”真実は、PiniaはVuex 4の次のバージョンと考えられることです.あるいはエヴァンは言った.
エバン・ユー
アットユウ
ピニャはデファクトVUEX 5です!この時点で、それは本当にネーミング/ブランディングの問題です.
08 : 49 AM - 2021年11月24日
PiniaはVUEXと多くの類似点を共有します、しかし、それはより単純です、安全で拡張可能なタイプ!
あなたがまだそれを試みていないならば、チェックアウトthe docs 始めましょう!
オブジェクトと関数の格納
ピアニアとのストアを作成する2つの方法があります.
オブジェクト構文:
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state: () => ({
counter: 0,
}),
getters: {
doubleCount: (state) => state.counter * 2,
},
actions: {
increment() {
this.counter++
},
}
})
関数構文import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useStore = defineStore('main', () => {
const counter = ref(0)
const doubleCounter = computed(() => counter.value * 2)
function increment() {
counter.value++
}
return {
counter,
doubleCounter,
increment
}
})
オブジェクト構文は、VUEXと非常によく似ています.関数の構文はsetup()
反応性を手動で定義する方法オブジェクト構文でストアをリセットする方法
オブジェクトの構文を使用する場合は、単に
$reset
メソッド:<script setup>
import { useStore } from './useStore'
const store = useStore()
store.$reset // 👈
</script>
しかし、組み込み関数$reset
メソッドは単にエラーをスローします:🍍: Store "main" is build using the setup syntax and does not implement $reset().
機能構文で店をリセットする方法
作るために
$reset
関数構文を使用して、Piniaプラグインを作成します.✨リセットストア.js
import cloneDeep from 'lodash.clonedeep'
export default function resetStore({ store }) {
const initialState = cloneDeep(store.$state)
store.$reset = () => store.$patch(cloneDeep(initialState))
}
ここでは、私たちは深く店の初期の状態をコピーしますlodash.clonedeep そして、我々は$reset
状態を初期値に設定する関数.コピー自体への参照を削除するには、再び状態を深くコピーすることが重要です.With
store.$patch
同時に複数の変更を適用します.Read more on the docs .で
main.js
またはPINIAをどこでも初期化します.// ...
import { resetStore } from './reset-store'
//...
const pinia = createPinia()
pinia.use(resetStore)
app.use(pinia)
//...
デモを見るhere on Stackblitz またはembed :Learn more about Pinia plugins
結論
すごい!オブジェクトや関数の構文を使用しても問題はない.
$reset
メソッドワークス!🥳🥳私は、そこで最高のVue - devsに感謝したいですhis answer on StackOverflow .
Reference
この問題について(Pinia:機能/セットアップ構文で作成された店舗のリセット方法), 我々は、より多くの情報をここで見つけました https://dev.to/the_one/pinia-how-to-reset-stores-created-with-functionsetup-syntax-1b74テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol