如何在Vue 3中的Vue Router中获取cookie?这在 router/index.js 中未定义

Com*_*wan 3 javascript session-cookies vue.js vuejs3

使用案例:使用express作为API后端的Vue3应用程序。Express 使用express-sessions 建立服务器端会话,该会话发送到浏览器并在每个后续请求中接收。

我正在尝试创建一个路由防护,以防止在会话 cookie 不存在时访问某些路由。

"vue": "^3.0.11",
"vue3-cookies": "1.0.1",
Run Code Online (Sandbox Code Playgroud)

我已经安装了以下 NPM 包

https://www.npmjs.com/package/vue3-cookies

然后在main.js

import VueCookies from 'vue3-cookies'
app.use(VueCookies);
Run Code Online (Sandbox Code Playgroud)

然后在router/index.js

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
Run Code Online (Sandbox Code Playgroud)

我试过了

this.$cookies.get('_ga')
Vue.$cookies.get('_ga')
window.$cookies.get('_ga')
Run Code Online (Sandbox Code Playgroud)

没有工作。

我也尝试过将 Vue 导入到 index.js 文件中,但失败了,可能是因为在 Vue3 中你无法将 Vue 导入到组件中Vue.js 3: Cannot import Vue global object

问题好像是this,Vue和window都是未定义的。我也尝试过这里的解决方案`this` undefined in vue-router beforeEach

router.beforeEach((to,from,next) => {
  console.log(router.app); //still undefined!
});
Run Code Online (Sandbox Code Playgroud)

帮助!

小智 8

这对我有用:

//router.js
import { useCookies } from "vue3-cookies";
const { cookies } = useCookies();

console.log(cookies.get('...'));
Run Code Online (Sandbox Code Playgroud)