前提
vue3で現状vuexを使っていたのですが、それをpiniaに変更しようとしています。
router/index.tsというルーティングを管理するファイルと
network/httpClient.tsというaxiosを管理するファイルが有り、このあたりでエラーが出た場合アラートを出したいり、ログインの管理をしています。
ただこれらのコンポーネント以外のファイルでstoreを呼び出すと以下のエラーが出ます。
storeの呼び出し
import { useAlertStore } from '../store/alert'; const alertStore = useAlertStore();
ブラウザのコンソールエラー
main.js:21 Uncaught Error: [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia? const pinia = createPinia() app.use(pinia) This will fail in production.
試したこと
try1) 新しくcreatePiniaする
そこで
https://qiita.com/Naoto_Ito/items/ede2b0a09f474df5e704
を参考に
import { setActivePinia, createPinia } from 'pinia' import { useMyStore } from './myStore' // 方法1:Piniaインスタンスを作って普通に注入 const pinia = createPinia() const myStore = useMyStore(pinia) // 方法2:setActivePinia()を利用 setActivePinia(createPinia()) const myStore = useMyStore()
追加しました。
すると方法1の方ではエラーは出なくなったのですが、そこで呼び出したactionの内容をコンポーネントで呼び出ししても、影響がありませんでした。
方法2では解消しませんでした。
try2) vueのpluginを読み込むときに使っているpiniaのインスタンスをstoreの引数に渡してみた。
const app = createApp(App) import { createPinia } from 'pinia' const pinia = createPinia() app.use(pinia) app.mount('#app') import { useAlertStore } from './store/alert'; const alertStore = useAlertStore(pinia); class HttpClient { alertStore.openAlert({ text: 'TEST', type: "error" }) ....省略 const httpClient = new HttpClient(); app.config.globalProperties.$httpClient = httpClient
これでうまく動作しました。
main.tsのpluginをuseしたときにpiniaのインスタンスと同じものを使えば良さそう。
ただそれだとHttpClientをvueコンポーネントの外で使うことができない。
例)vue コンポーネント内でならthisで呼べるようになっている。
const res = await this.$httpClient.put(..);
しかしstoreなどvueコンポーネント外で使う場合はimportする場合があるがそうするとstoreが使えないということになる。
import { httpClient } from "@/admin/network/httpClient";
なにか良い解決方法などあれば教えていただきたいです。
補足
SPAです。
参考
githubの同様っぽい質問
- https://github.com/vuejs/pinia/discussions/971
- https://pinia.vuejs.org/core-concepts/outside-component-usage.html#single-page-applications
参考1
- https://jasonwatmore.com/post/2022/05/26/vue-3-pinia-jwt-authentication-tutorial-example
- https://github.com/cornflourblue/vue-3-pinia-jwt-authentication-example
参考2
- https://jasonwatmore.com/post/2022/07/25/vue-3-pinia-user-registration-and-login-example-tutorial
- https://github.com/cornflourblue/vue-3-pinia-registration-login-example
ここの参考ではhelperなどのコンポーネント外でstoreを呼び出して使っているようなのですが、なぜエラーが起きずに使えているのか不明
https://github.com/cornflourblue/vue-3-pinia-registration-login-example/blob/master/src/helpers/fetch-wrapper.js
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。