useStore() と this.$store の違いthis.$store(オプションAPI・クラスコンポーネント) |
useStore()(Composition API) |
|
|---|---|---|
| どこで使う? | コンポーネントの中 (this が使える場所) |
setup() の中 |
| 使い方 | this.$store.state.count など |
const store = useStore(); store.state.count |
| 型付けのしやすさ | 補完はできるが型推論はやや弱い | useStore() を型付きで自作すれば強い |
| Composition API対応 | ❌ できない | ✅ できる |
| グローバル変数っぽさ | あり (this.$store でどこでも取れる) |
明示的に store を取るのでわかりやすい |
this.$store:
→ でっかい冷蔵庫が家にひとつ。取りに行くのは自由。
→ でも誰が何を使ってるかはちょっとわかりにくい。
useStore():
→ 必要なときに「はい、これがあなた用の冷蔵庫ですよ」と手渡しする。
→ 誰が何を使うか明確。
this.$store の使い方(オプションAPI・クラスコンポーネント)export default Vue.extend({
methods: {
increment() {
// 直接this.$storeでアクセス
this.$store.commit('increment');
}
}
});
useStore() の使い方(Composition API)<script lang="ts" setup>
import { useStore } from '@/composables/useStore'; // 型付きのuseStore
const store = useStore();
// stateを読む
const count = store.state.count;
// mutationを呼ぶ
store.commit('increment');
</script>
this.$store |
useStore() |
|
|---|---|---|
| グローバルから取れる | できる | 明示的に setup() で取る必要がある |
setup() 内で使えるか |
使えない(thisがない) |
使える |
| 型補完 | 弱め($storeはanyになりがち) |
型付き useStore で強い補完が効く |
| 保守性 | 大規模になるとどこで使ってるかわからなくなる | どこで使っているか明確 |
this.$store を使おうとすると…