簡體   English   中英

在 vuex 4.x 中使用`useStore` API

[英]Using `useStore` API with vuex 4.x

  1. 按照官方示例導出自己的useStore ,然后在組件中使用。
import { createStore, Store,  useStore as baseUseStore } from 'vuex';

export const key: InjectionKey<Store<RootState>> = Symbol();

export function useStore() {
  return baseUseStore(key);
}

在組件中使用

setup() {
  const store = useStore();
  const onClick = () => {
    console.log(store)
    store.dispatch('user/getUserInfo');
  }
  return {
    onClick,
  }
},
  1. 運行后, store未定義。
  2. 我在methods屬性中使用時可以正常獲取
methods: {
  login() {
    this.$store.dispatch('user/getToken')
  }
}
  1. 為什么? 如何修復它

在那個簡化useStore使用教程中,你仍然需要像他們一樣在main.ts中注冊storekey 如果您不這樣做,您將得到未定義:

// main.ts
import { store, key } from './store'

const app = createApp({ ... })

// pass the injection key
app.use(store, key)

原因是baseUseStore(key)在完成之前沒有任何意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM