js-cookie 和 nprogress插件的使用

本文介绍了如何使用js-cookie库进行Cookie操作,包括设置、获取和删除,并详细讲解了存储JSON数据的方法。同时,介绍了nprogress插件,用于创建类似YouTube的加载进度条,提供流畅的用户体验。通过Nprogress的start(), done(), set()和inc()方法,可以轻松控制进度条的显示和进度变化。

js-cookie

使用步骤:

  • 下载 npm i js-cookie

  • 导入 import Cookiejs from 'js-cookie'

  • 获取: Cookiejs.get(key)

  • 设置:Cookiejs.set(key,value)

  • 删除:Cookiejs.remove(key)

  • json相关

js-cookie允许你向cookie中存储json信息。

如果你通过set方法,传入Array或类似对象,而不是简单的string,那么js-cookie会将你传入的数据用JSON.stringify转换为string保存。

Cookiejs.set('name', { foo: 'bar' });
Cookiejs.get('name'); // => '{"foo":"bar"}'
Cookiejs.get(); // => { name: '{"foo":"bar"}' }

如果你用getJSON方法获取cookie,那么js-cookie会用JSON.parse解析string并返回。

Cookiejs.getJSON('name'); // => { foo: 'bar' }
Cookiejs.getJSON(); // => { name: { foo: 'bar' } }

set方法支持的属性

  1. expires
    定义有效期。如果传入Number,那么单位为天,你也可以传入一个Date对象,表示有效期至Date指定时间。默认情况下cookie有效期截止至用户退出浏览器。

  2. path
    string,表示此cookie对哪个地址可见。默认为”/”。

  3. domain
    string,表示此cookie对哪个域名可见。设置后cookie会对所有子域名可见。默认为对创建此cookie的域名和子域名可见。

  4. secure
    true或false,表示cookie传输是否仅支持https。默认为不要求协议必须为https。

nprogress

这是一个类似youtube、Medium等网站上的小进度条插件。纳米级的进度条,涓涓细流动画告诉你的用户,一些事情正在发生!

1:安装 yarn add nprogress   ||     npm install --save nprogress

2:导入 import Nprogress from 'nprogress'

           import 'nprogress/nprogress.css'

使用

直接调用 start()或者done()来控制进度条。

NProgress.start();
NProgress.done();

可以通过调用 .set(n)来设置进度,n是0-1的数字。

NProgress.set(0.0);     // Sorta same as .start()
NProgress.set(0.4);
NProgress.set(1.0);     // Sorta same as .done()

可以使用inc()随机增长进度条,注意,这个方法永远不会让进度条达到100%。

NProgress.inc();

通过使用done()让进度条关闭。

NProgress.done(true);

let path = require('path') const webpack = require('webpack') const ThemeColorReplacer = require('webpack-theme-color-replacer') const {getThemeColors, modifyVars} = require('./src/utils/themeUtil') const {resolveCss} = require('./src/utils/theme-color-replacer-extend') const CompressionWebpackPlugin = require('compression-webpack-plugin') const productionGzipExtensions = ['js', 'css'] const isProd = process.env.NODE_ENV === 'production' const timeStamp = new Date().getTime(); const assetsCDN = { // webpack build externals externals: { vue: 'Vue', 'vue-router': 'VueRouter', vuex: 'Vuex', axios: 'axios', nprogress: 'NProgress', clipboard: 'ClipboardJS', '@antv/data-set': 'DataSet', 'js-cookie': 'Cookies' }, css: [], js: [ // '//cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.min.js', // '//cdn.jsdelivr.net/npm/vue-router@3.3.4/dist/vue-router.min.js', // '//cdn.jsdelivr.net/npm/vuex@3.4.0/dist/vuex.min.js', // '//cdn.jsdelivr.net/npm/axios@0.19.2/dist/axios.min.js', // '//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js', // '//cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js', // '//cdn.jsdelivr.net/npm/@antv/data-set@0.11.4/build/data-set.min.js', // '//cdn.jsdelivr.net/npm/js-cookie@2.2.1/src/js.cookie.min.js' './js/vue/vue.min.js', './js/vue-router/vue-router.min.js', './js/vuex/vuex.min.js', './js/axios/axios.min.js', './js/clipboard/clipboard.min.js', './js/@antv/data-set.js', './js/nprogress/nprogress.min.js', './js/js-cookie/js.cookie.min.js', ] } module.exports = { devServer: { proxy: { '/api': { //此处要与 /services/api.js 中的 API_PROXY_PREFIX 值保持一致 target: process.env.VUE_APP_API_BASE_URL, changeOrigin: true, pathRewrite: { '^/api': '' } } } }, pluginOptions: { 'style-resources-loader': { preProcessor: 'less', patterns: [path.resolve(__dirname, "./src/theme/theme.less")], } }, configureWebpack: config => { config.entry.app = ["babel-polyfill", "whatwg-fetch", "./src/main.js"]; // 打包编译后修改 js 文件名 config.output.filename = `static/js/[name].${timeStamp}.js`; config.output.chunkFilename = `static/js/[name].${timeStamp}.js`; config.performance = { hints: false } config.plugins.push( new ThemeColorReplacer({ fileName: 'css/theme-colors-[contenthash:8].css', matchColors: getThemeColors(), injectCss: true, resolveCss }) ) // Ignore all locale files of moment.js config.plugins.push(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)) // 生产环境下将资源压缩成gzip格式 if (isProd) { // add `CompressionWebpack` plugin to webpack plugins config.plugins.push(new CompressionWebpackPlugin({ algorithm: 'gzip', test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'), threshold: 10240, minRatio: 0.8 })) } // if prod, add externals if (isProd) { config.externals = assetsCDN.externals } }, chainWebpack: config => { // 生产环境下关闭css压缩的 colormin 项,因为此项优化与主题色替换功能冲突 if (isProd) { config.plugin('optimize-css') .tap(args => { args[0].cssnanoOptions.preset[1].colormin = false return args }) } // 生产环境下使用CDN if (isProd) { config.plugin('html') .tap(args => { args[0].cdn = assetsCDN return args }) } }, css: { loaderOptions: { less: { lessOptions: { modifyVars: modifyVars(), javascriptEnabled: true } } }, // 打包时的CSS文件 extract: { // 打包编译后修改 css 文件名 filename: `static/css/[name].${timeStamp}.css`, chunkFilename: `static/css/[name].${timeStamp}.css` }, }, // publicPath: process.env.VUE_APP_PUBLIC_PATH, publicPath: './', outputDir: 'dist', assetsDir: 'static', productionSourceMap: false, runtimeCompiler: true }
最新发布
09-06
Property "center" must be accessed with "$data.center" because properties starting with "$" or "_" are not proxied in the Vue instance to prevent conflicts with Vue internalsSee: https://vuejs.org/v2/api/#data import router from './router' import store from './store' import { Message } from 'element-ui' import NProgress from 'nprogress' // progress bar import 'nprogress/nprogress.css' // progress bar style import { getToken } from '@/utils/auth' // get token from cookie import getPageTitle from '@/utils/get-page-title' NProgress.configure({ showSpinner: false }) // NProgress Configuration const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist router.beforeEach(async(to, from, next) => { // start progress bar NProgress.start() // set page title document.title = getPageTitle(to.meta.title) // determine whether the user has logged in const hasToken = getToken() if (hasToken) { if (to.path === '/login') { // if is logged in, redirect to the home page next({ path: '/' }) NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939 } else { // determine whether the user has obtained his permission roles through getInfo const hasRoles = store.getters.roles && store.getters.roles.length > 0 if (hasRoles) { next() } else { try { // get user info // note: roles must be a object array! such as: ['admin'] or ,['developer','editor'] const { roles } = await store.dispatch('user/getInfo') // generate accessible routes map based on roles const accessRoutes = await store.dispatch('permission/generateRoutes', roles) // dynamically add accessible routes router.addRoutes(accessRoutes) console.log("store===",store) // hack method to ensure that addRoutes is complete // set the replace: true, so the navigation will not leave a history record next({ ...to, replace: true }) } catch (error) { // remove token and go to login page to re-login await store.dispatch('user/resetToken') Message.error(error || 'Has Error') next(`/login?redirect=${to.path}`) NProgress.done() } } } } else { /* has no token*/ if (whiteList.indexOf(to.path) !== -1) { // in the free login whitelist, go directly next() } else { // other pages that do not have permission to access are redirected to the login page. next(`/login?redirect=${to.path}`) NProgress.done() } } }) router.afterEach(() => { // finish progress bar NProgress.done() })
08-11
{ "name": "vue-admin-template", "version": "4.4.0", "description": "A vue admin template with Element UI & axios & iconfont & permission control & lint", "author": "Pan <panfree23@gmail.com>", "scripts": { "dev": "vue-cli-service serve", "build:prod": "vue-cli-service build", "build:stage": "vue-cli-service build --mode staging", "preview": "node build/index.js --preview", "svgo": "svgo -f src/icons/svg --config=src/icons/svgo.yml", "lint": "eslint --ext .js,.vue src", "test:unit": "jest --clearCache && vue-cli-service test:unit", "test:ci": "npm run lint && npm run test:unit" }, "dependencies": { "axios": "0.18.1", "core-js": "3.6.5", "element-ui": "2.13.2", "js-cookie": "2.2.0", "normalize.css": "7.0.0", "nprogress": "0.2.0", "path-to-regexp": "2.4.0", "vue": "2.6.10", "vue-router": "3.0.6", "vuex": "3.1.0" }, "devDependencies": { "@vue/cli-plugin-babel": "4.4.4", "@vue/cli-plugin-eslint": "4.4.4", "@vue/cli-plugin-unit-jest": "4.4.4", "@vue/cli-service": "4.4.4", "@vue/test-utils": "1.0.0-beta.29", "autoprefixer": "9.5.1", "babel-eslint": "10.1.0", "babel-jest": "23.6.0", "babel-plugin-dynamic-import-node": "2.3.3", "chalk": "2.4.2", "connect": "3.6.6", "eslint": "6.7.2", "eslint-plugin-vue": "6.2.2", "html-webpack-plugin": "3.2.0", "mockjs": "1.0.1-beta3", "runjs": "4.3.2", "sass": "1.26.8", "sass-loader": "8.0.2", "script-ext-html-webpack-plugin": "2.1.3", "serve-static": "1.13.2", "svg-sprite-loader": "4.1.3", "svgo": "1.2.2", "vue-template-compiler": "2.6.10" }, "browserslist": [ "> 1%", "last 2 versions" ], "engines": { "node": ">=8.9", "npm": ">= 3.0.0" }, "license": "MIT" }
03-18
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值