Javascript 如何在Vue 3中的Vue路由器中获取cookie?这在router/index.js中未定义
用例:使用express作为API后端的Vue3应用程序。Express使用Express会话建立服务器端会话,该会话发送到浏览器,并在后续的每个请求中接收 我正在尝试创建一个路由保护,以防止在会话cookie不存在时访问某些路由Javascript 如何在Vue 3中的Vue路由器中获取cookie?这在router/index.js中未定义,javascript,vue.js,session-cookies,vuejs3,Javascript,Vue.js,Session Cookies,Vuejs3,用例:使用express作为API后端的Vue3应用程序。Express使用Express会话建立服务器端会话,该会话发送到浏览器,并在后续的每个请求中接收 我正在尝试创建一个路由保护,以防止在会话cookie不存在时访问某些路由 "vue": "^3.0.11", "vue3-cookies": "1.0.1", 我已经安装了以下NPM包 然后在main.js中 import VueCookies from '
"vue": "^3.0.11",
"vue3-cookies": "1.0.1",
我已经安装了以下NPM包
然后在main.js中
import VueCookies from 'vue3-cookies'
app.use(VueCookies);
function requireAuth(to,from,next){
console.log(this);
console.log(this.$cookies.get('_ga'))
next();
}
const routes = [
{
path: '/',
name: 'ProtectedRoute',
component: ProtectedRoute,
beforeEnter:requireAuth
}
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
Error: [Vue Router warn]: Unexpected error when starting the router: TypeError: Cannot read property '$cookies' of undefined
然后在router/index.js中
import VueCookies from 'vue3-cookies'
app.use(VueCookies);
function requireAuth(to,from,next){
console.log(this);
console.log(this.$cookies.get('_ga'))
next();
}
const routes = [
{
path: '/',
name: 'ProtectedRoute',
component: ProtectedRoute,
beforeEnter:requireAuth
}
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
Error: [Vue Router warn]: Unexpected error when starting the router: TypeError: Cannot read property '$cookies' of undefined
我试过了
this.$cookies.get('_ga')
Vue.$cookies.get('_ga')
window.$cookies.get('_ga')
没用
我还尝试将Vue导入index.js文件,但失败了,可能是因为在Vue3中无法将Vue导入组件
问题似乎是这个、Vue和窗口都未定义。我在这里也尝试过这个解决方案
救命啊 ,但您可以在设置路由器时自行添加:
//main.js
从“./路由器”导入路由器
常量应用程序=createApp(应用程序)
应用程序使用(路由器)
router.app=app
app.mount(“#app”)
然后在路由器配置脚本中,您可以使用该引用获取app.config.globalProperties.$cookies
(通过vue3 cookies
添加的全局文件):
//router.js
const router=createRouter({
历史记录:createWebHistory(),
路线
})
函数requireAuth(到、从、下一个){
const{$cookies}=router.app.config.globalProperties
console.log('u ga',$cookies.get('u ga'))
下一个()
}
导出默认路由器
你到底想实现什么目标?为什么您要在每次之前获取cookie?也可能是软件包有问题,您是否尝试过使用document.cookie
?看看它是否输出了什么?您的上下文是错误的,我认为您可以尝试使用Vue。$cookies(首先导入Vue)谢谢!这是正确的方法吗?这似乎有点老套。正确的方法是有争议的,但我同意这并不理想。将应用程序
连接到路由器
,因此我认为这是一种“vue”方式。