Pinia - 컴포넌트 외부에서 사용 시 (vue2)

clean·2022년 2월 22일
0

개발 환경

현재 개발 환경은 vue2+composition api 이다.
router에서 pinia에 있는 store를 호출하여 값을 꺼내올 일이 생겼는데 자꾸 스토어가 아직 설치되지 않았다는 에러가 발생했다.

컴포넌트 외에서 스토어 사용 시 공홈에서는 아래와 같이 사용하라고 되어있다.

// ❌ 이러면 임포트 안됨 
const store = useStore()

router.beforeEach((to, from, next) => {
  // we wanted to use the store here
  if (store.isLoggedIn) next()
  else next('/login')
})

// 이렇게 사용
router.beforeEach((to) => {
  // ✅ This will work because the router starts its navigation after
  // the router is installed and pinia will be installed too
  const store = useStore()

  if (to.meta.requiresAuth && !store.isLoggedIn) return '/login'
})
  • 근데 나와 같은 경우 위와 같이 적용해도 같은 에러가 발생했다.

    vue-router.esm.js:16 [vue-router] uncaught error during route navigation:
    vue-router.esm.js:2314 Error: [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?

찾아보니 나와 비슷한 문제를 겪는 사람들 발견

시도 1

  • Vue.use(router)를 Vue.use(PiniaPlugin) 다음에 호출하라고 했으나... 왜인지 아무리 순서를 바꿔도 router에 정의한 beforeEach 가 호출된 후에 Pinia installed! 가 찍혔다. 🤔
  • Pinia가 installed 된 다음 router가 활성화 되어야 할 것 같은데 .....

시도 2 (해결)

  • main.ts 에서 useStore(pinia) 를 호출해줬더니 beforeEach에서 useAStore 사용 시 더이상 에러가 발생하지 않았다.

1개의 댓글

comment-user-thumbnail
2022년 8월 18일

안녕하세요 올려주신 글 잘보았습니다 그럼 main.js 자체에서도 사용가능할까요?

첫 시작시 토큰이나 특별한 값이 있으면 로그인 처리 하려고 하는데

main에서 처리해야 될것같아서요

답글 달기