Vue 3 & Pinia 状态管理(8) - 组件外使用存储(完)
嗨,我是温新,一名 PHPer。
本篇目标:了解什么是 Pinia
Pinia 官方文档:https://pinia.web3doc.top/introduction.html
在学习的这些案例中,都是在组件内使用 store
,如何是在组件外使用,会出现错误。
单页应用程序
确保始终应用此功能的最简单方法是延迟调用 useStore()
,方法是将它们放在安装 pinia 后始终运行的函数中。
import { useUserStore } from '@/stores/user'
import { createApp } from 'vue'
import App from './App.vue'
// 失败,因为它是在创建 pinia 之前调用的
const userStore = useUserStore()
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
// 有效,因为 pinia 实例现在处于活动状态
const userStore = useUserStore()
Vue Router 的导航守卫内部的 store 的例:
import { createRouter } from 'vue-router'
const router = createRouter({
// ...
})
// 根据导入的顺序,这将失败
const store = useStore()
router.beforeEach((to, from, next) => {
// 我们想在这里使用 store
if (store.isLoggedIn) next()
else next('/login')
})
router.beforeEach((to) => {
// 这将起作用,因为路由器在之后开始导航
// 路由已安装,pinia 也将安装
const store = useStore()
if (to.meta.requiresAuth && !store.isLoggedIn) return '/login'
})
2023-07-23 完
请登录后再评论