Vue谷歌登录后刷新信息丢失,引入vue-cookie报Vue.use is not a function如何解决
报错原因及修复方法
报错根因
你触发Vue.use is not a function错误是因为存在3个操作问题:
- 同时混用CDN引入Vue和CommonJS的
require('vue')语法,两种引入方式冲突导致拿到的Vue对象异常 - 把插件注册逻辑
Vue.use(VueCookie)写在了单文件组件的<script>顶层,该操作应该在项目入口文件(如main.js)全局执行,不能在组件内写 - 在组件顶层直接执行
this.$cookie.set,此时组件还未初始化,this指向不是Vue实例,必然报错
修复步骤
- 先删除App.vue文件
<script>标签内以下冗余代码:
var Vue = require('vue'); var VueCookie = require('vue-cookie'); // Tell Vue to use the plugin Vue.use(VueCookie); // From some method in one of your Vue components this.$cookie.set('test', 'Hello world!', 1); // This will set a cookie with the name 'test' and the value 'Hello world!' that expires in one day // To get the value of a cookie use this.$cookie.get('test'); // To delete a cookie use this.$cookie.delete('test');
全局注册vue-cookies插件:
- 如果你是用npm安装依赖的项目,在入口文件main.js中添加如下代码:
import Vue from 'vue' import VueCookies from 'vue-cookies' Vue.use(VueCookies) // 可全局配置cookie默认过期时间,此处设为7天 Vue.$cookies.config('7d')- 如果你是纯CDN引入的项目,只要保证引入顺序是先引入Vue、再引入vue-cookies即可,插件会自动注册不需要手动调用
Vue.use
修改App组件逻辑实现登录状态持久化:
export default { name: "App", data() { return { isLogin: false, }; }, // 页面初始化/刷新时从cookie读取登录状态 mounted() { this.isLogin = this.$cookies.get('g_login_status') === '1' }, methods: { async logOut() { const result = await this.$gAuth.signOut(); this.isLogin = false; // 退出登录时清除cookie this.$cookies.remove('g_login_status') this.$cookies.remove('g_user_id') console.log(`result`, result); }, async login() { const googleUser = await this.$gAuth.signIn(); this.isLogin = this.$gAuth.isAuthorized; // 登录成功后写入cookie if(this.isLogin) { this.$cookies.set('g_login_status', '1', '7d') // 需要持久化的用户参数可以一并存入,比如用户ID this.$cookies.set('g_user_id', googleUser.getId(), '7d') } }, }, };
更优的登录会话存储方案
- 纯前端无后端场景:优先用
localStorage存储,操作比cookie更简单,不会每次请求都自动携带在请求头里,性能更好,只要存非敏感的公开用户信息完全够用,操作语法:- 存:
localStorage.setItem('g_login_status', '1') - 取:
localStorage.getItem('g_login_status') - 删:
localStorage.removeItem('g_login_status')
- 存:
- 临时会话场景:用
sessionStorage,关闭浏览器后数据自动清除,适合需要每次打开浏览器重新登录的场景 - 有后端服务场景:最优方案是谷歌登录成功后把授权凭证传给后端,由后端生成JWT令牌或者session标识返回给前端存储,后端统一做登录状态校验,避免前端伪造登录状态,安全性最高。
内容的提问来源于stack exchange,提问作者Yagel
相关产品推荐
相关产品推荐

