thi*_*ebo 9 vue-router vuejs3 pinia
我正在使用 Vuejs 3、vuerouter 4 和 pinia,并尝试在某些路线中放置导航防护,按照文档中的示例(如果用户未经身份验证并且不在登录页面上,则将用户发送到登录页面获得身份验证)。关于在组件之外使用 pinia 的pinia 文档中也对此进行了解释。但我无法理解它。
我使用的商店目前很简单(返回 false 或 true isAuthenticated):
//authStore.js
import { defineStore } from "pinia";
export const useAuthStore = defineStore( 'AuthStore', {
state: () => {
return {
isAuthenticated: false
}
}
})
Run Code Online (Sandbox Code Playgroud)
isAuthenticated我想在一个beforeEnter中使用这个routes/index.js
在 main.js 中:
import { useAuthStore } from '@/stores/authStore'
import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router'
import { createPinia } from 'pinia'
const app = createApp(App)
app.use(createPinia()).use(router)
app.mount('#app')
// I'm not using authStore in this file, so this raises an error:
const authStore = useAuthStore()
Run Code Online (Sandbox Code Playgroud)
在 router/index.js 中:
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
// path for login page,
{
path: '/adm/home',
name: 'AdmView',
component: () => import('@/views/adm/AdmView.vue'),
beforeEnter: (to) => {
// error: authStore is not defined
const isAuthenticated = authStore
if ( !isAuthenticated && to.name !== 'login-adm' ) {
return { name: 'login-adm' }
}
}
},
// other paths
]
Run Code Online (Sandbox Code Playgroud)
您按预期authStore.js导出useAuthStore,但未按要求调用它。
authStore is not defined因为是您的身份验证存储的文件名 - 相反,您应该执行从该文件导出的authStore函数:useAuthStore
const authStore = useAuthStore();
console.log('Is authenticated?', authStore.isAuthenticated);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5628 次 |
| 最近记录: |