最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

在Vue中如何使用Cookie操作實(shí)例

 更新時(shí)間:2017年07月27日 09:21:07   作者:陳楠酒肆  
這篇文章主要介紹了在Vue中如何使用Cookie操作實(shí)例的相關(guān)資料,需要的朋友可以參考下

大家好,由于公司忙著趕項(xiàng)目,導(dǎo)致有段時(shí)間沒(méi)有發(fā)布新文章了。今天我想跟大家談?wù)凜ookie的使用。同樣,這個(gè)Cookie的使用方法是我從公司的項(xiàng)目中抽出來(lái)的,為了能讓大家看懂,我會(huì)盡量寫(xiě)詳細(xì)點(diǎn)。廢話少說(shuō),我們直接進(jìn)入正題。

一、安裝Cookie

在Vue2.0下,這個(gè)貌似已經(jīng)不需要安裝了。因?yàn)楫?dāng)你創(chuàng)建一個(gè)項(xiàng)目的時(shí)候,npm install 已經(jīng)為我們安裝好了。我的安裝方式如下:

# 全局安裝 vue-cli
$ npm install --global vue-cli
# 創(chuàng)建一個(gè)基于 webpack 模板的新項(xiàng)目
$ vue init webpack my-project
# 安裝依賴,走你
$ cd my-project
$ npm install

這是我創(chuàng)建好的目錄結(jié)構(gòu),大家可以看一下:


項(xiàng)目結(jié)構(gòu)

二、封裝Cookie方法

在util文件夾下,我們創(chuàng)建util.js文件,然后上代碼

//獲取cookie、
export function getCookie(name) {
 var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
 if (arr = document.cookie.match(reg))
  return (arr[2]);
 else
  return null;
}

//設(shè)置cookie,增加到vue實(shí)例方便全局調(diào)用
export function setCookie (c_name, value, expiredays) {
 var exdate = new Date();
 exdate.setDate(exdate.getDate() + expiredays);
 document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
};

//刪除cookie
export function delCookie (name) {
 var exp = new Date();
 exp.setTime(exp.getTime() - 1);
 var cval = getCookie(name);
 if (cval != null)
  document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};

三、在HTTP中把Cookie傳到后臺(tái)

關(guān)于這點(diǎn),我需要說(shuō)明一下,我們這里使用的是axios進(jìn)行HTTP傳輸數(shù)據(jù),為了更好的使用axios,我們?cè)趗til文件夾下創(chuàng)建http.js文件,然后封裝GET,POST等方法,代碼如下:

import axios from 'axios' //引用axios
import {getCookie} from './util' //引用剛才我們創(chuàng)建的util.js文件,并使用getCookie方法

// axios 配置
axios.defaults.timeout = 5000; 
axios.defaults.baseURL = 'http://localhost/pjm-shield-api/public/v1/'; //這是調(diào)用數(shù)據(jù)接口

// http request 攔截器,通過(guò)這個(gè),我們就可以把Cookie傳到后臺(tái)
axios.interceptors.request.use(
  config => {
    const token = getCookie('session'); //獲取Cookie
    config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded' //設(shè)置跨域頭部
    };
    if (token) {
      config.params = {'token': token} //后臺(tái)接收的參數(shù),后面我們將說(shuō)明后臺(tái)如何接收
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);


// http response 攔截器
axios.interceptors.response.use(
  response => {
//response.data.errCode是我接口返回的值,如果值為2,說(shuō)明Cookie丟失,然后跳轉(zhuǎn)到登錄頁(yè),這里根據(jù)大家自己的情況來(lái)設(shè)定
    if(response.data.errCode == 2) {
      router.push({
        path: '/login',
        query: {redirect: router.currentRoute.fullPath} //從哪個(gè)頁(yè)面跳轉(zhuǎn)
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error.response.data)
  });

export default axios;

/**
 * fetch 請(qǐng)求方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function fetch(url, params = {}) {

  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}

/**
 * post 請(qǐng)求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      })
  })
}

/**
 * patch 方法封裝
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      })
  })
}

/**
 * put 方法封裝
 * @param url
 * @param data
 * @returns {Promise}
 */
export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      })
  })
}

四、在登錄組件使用Cookie

由于登錄組件我用的是Element-ui布局,對(duì)應(yīng)不熟悉Element-ui的朋友們,可以去惡補(bǔ)一下。后面我們將講解如何使用它進(jìn)行布局。登錄組件的代碼如下:

<template>
 <el-form ref="AccountFrom" :model="account" :rules="rules" label-position="left" label-width="0px"
      class="demo-ruleForm login-container">
  <h3 class="title">后臺(tái)管理系統(tǒng)</h3>
  <el-form-item prop="u_telephone">
   <el-input type="text" v-model="account.u_telephone" auto-complete="off" placeholder="請(qǐng)輸入賬號(hào)"></el-input>
  </el-form-item>
  <el-form-item prod="u_password">
   <el-input type="password" v-model="account.u_password" auto-complete="off" placeholder="請(qǐng)輸入密碼"></el-input>
  </el-form-item>
  <el-form-item style="width:100%;">
   <el-button type="primary" style="width:100%" @click="handleLogin" :loading="logining">登錄</el-button>
  </el-form-item>
 </el-form>
</template>

<script>
 export default {
  data() {
   return {
    logining: false,
    account: {
     u_telephone:'',
     u_password:''
    },
    //表單驗(yàn)證規(guī)則
    rules: {
     u_telephone: [
      {required: true, message:'請(qǐng)輸入賬號(hào)',trigger: 'blur'}
     ],
     u_password: [
      {required: true,message:'請(qǐng)輸入密碼',trigger: 'blur'}
     ]
    }
   }
  },
  mounted() {
   //初始化
  },
  methods: {
   handleLogin() {
    this.$refs.AccountFrom.validate((valid) => {
     if(valid) {
      this.logining = true;
//其中 'm/login' 為調(diào)用的接口,this.account為參數(shù)
      this.$post('m/login',this.account).then(res => {
       this.logining = false;
       if(res.errCode !== 200) {
        this.$message({
         message: res.errMsg,
         type:'error'
        });
       } else {
        let expireDays = 1000 * 60 * 60 ;
        this.setCookie('session',res.errData.token,expireDays); //設(shè)置Session
        this.setCookie('u_uuid',res.errData.u_uuid,expireDays); //設(shè)置用戶編號(hào)
        if(this.$route.query.redirect) {
         this.$router.push(this.$route.query.redirect);
        } else {
         this.$router.push('/home'); //跳轉(zhuǎn)用戶中心頁(yè)
        }
       }
      });
     } else {
      console.log('error submit');
      return false;
     }
    });
   }
  }
 }
</script>

五、在路由中驗(yàn)證token存不存在,不存在的話會(huì)到登錄頁(yè)

在 router--index.js中設(shè)置路由,代碼如下:

import Vue from 'vue'
import Router from 'vue-router'
import {post,fetch,patch,put} from '@/util/http'
import {delCookie,getCookie} from '@/util/util'

import Index from '@/views/index/Index' //首頁(yè)
import Home from '@/views/index/Home' //主頁(yè)
import right from '@/components/UserRight' //右側(cè)
import userlist from '@/views/user/UserList' //用戶列表
import usercert from '@/views/user/Certification' //用戶審核
import userlook from '@/views/user/UserLook' //用戶查看
import usercertlook from '@/views/user/UserCertLook' //用戶審核查看

import sellbill from '@/views/ticket/SellBill' 
import buybill from '@/views/ticket/BuyBill'
import changebill from '@/views/ticket/ChangeBill' 
import billlist from '@/views/bill/list' 
import billinfo from '@/views/bill/info' 
import addbill from '@/views/bill/add' 
import editsellbill from '@/views/ticket/EditSellBill' 

import ticketstatus from '@/views/ticket/TicketStatus' 
import addticket from '@/views/ticket/AddTicket' 
import userinfo from '@/views/user/UserInfo' //個(gè)人信息
import editpwd from '@/views/user/EditPwd' //修改密碼

Vue.use(Router);

const routes = [
 {
  path: '/',
  name:'登錄',
  component:Index
 },
 {
  path: '/',
  name: 'home',
  component: Home,
  redirect: '/home',
  leaf: true, //只有一個(gè)節(jié)點(diǎn)
  menuShow: true,
  iconCls: 'iconfont icon-home', //圖標(biāo)樣式
  children: [
   {path:'/home', component: right, name: '首頁(yè)', menuShow: true, meta:{requireAuth: true }}
  ]
 },
 {
  path: '/',
  component: Home,
  name: '用戶管理',
  menuShow: true,
  iconCls: 'iconfont icon-users',
  children: [
   {path: '/userlist', component: userlist, name: '用戶列表',  menuShow: true, meta:{requireAuth: true }},
   {path: '/usercert', component: usercert, name: '用戶認(rèn)證審核', menuShow: true, meta:{requireAuth: true }},
   {path: '/userlook', component: userlook, name: '查看用戶信息', menuShow: false,meta:{requireAuth: true}},
   {path: '/usercertlook', component: usercertlook, name: '用戶審核信息', menuShow: false,meta:{requireAuth: true}},
  ]
 },
 {
  path: '/',
  component: Home,
  name: '信息管理',
  menuShow: true,
  iconCls: 'iconfont icon-books',
  children: [
   {path: '/sellbill',  component: sellbill,  name: '賣票信息', menuShow: true, meta:{requireAuth: true }},
   {path: '/buybill',  component: buybill,  name: '買票信息', menuShow: true, meta:{requireAuth: true }},
   {path: '/changebill', component: changebill, name: '換票信息', menuShow: true, meta:{requireAuth: true }},
   {path: '/bill/editsellbill', component: editsellbill, name: '編輯賣票信息', menuShow: false, meta:{requireAuth: true}}
  ]
 },
 {
  path: '/bill',
  component: Home,
  name: '票據(jù)管理',
  menuShow: true,
  iconCls: 'iconfont icon-books',
  children: [
   {path: '/bill/list',  component: billlist,  name: '已開(kāi)票據(jù)列表', menuShow: true, meta:{requireAuth: true }},
   {path: '/bill/info',  component: billinfo,  name: '票據(jù)詳細(xì)頁(yè)', menuShow: false, meta:{requireAuth: true }},
   {path: '/bill/add',  component: addbill,  name: '新建開(kāi)票信息', menuShow: true, meta:{requireAuth: true }}

  ]
 },
 {
  path: '/',
  component: Home,
  name: '系統(tǒng)設(shè)置',
  menuShow: true,
  iconCls: 'iconfont icon-setting1',
  children: [
   {path: '/userinfo', component: userinfo, name: '個(gè)人信息', menuShow: true, meta:{requireAuth: true }},
   {path: '/editpwd', component: editpwd, name: '修改密碼', menuShow: true, meta:{requireAuth: true }}
  ]
 }
 ];

const router = new Router({
  routes
});

備注:請(qǐng)注意路由中的 meta:{requireAuth: true },這個(gè)配置,主要為下面的驗(yàn)證做服務(wù)。

if(to.meta.requireAuth),這段代碼意思就是說(shuō),如果requireAuth: true ,那就判斷用戶是否存在。

如果存在,就繼續(xù)執(zhí)行下面的操作,如果不存在,就刪除客戶端的Cookie,同時(shí)頁(yè)面跳轉(zhuǎn)到登錄頁(yè),代碼如下。

//這個(gè)是請(qǐng)求頁(yè)面路由的時(shí)候會(huì)驗(yàn)證token存不存在,不存在的話會(huì)到登錄頁(yè)
router.beforeEach((to, from, next) => {
 if(to.meta.requireAuth) {
  fetch('m/is/login').then(res => {
   if(res.errCode == 200) {
    next();
   } else {
    if(getCookie('session')) {
     delCookie('session');
    }
    if(getCookie('u_uuid')) {
     delCookie('u_uuid');
    }
    next({
     path: '/'
    });
   }
  });
 } else {
  next();
 }
});
export default router;


以上就是Cookie在項(xiàng)目中的使用,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Vue利用Web?Speech?API實(shí)現(xiàn)文字朗讀功能

    Vue利用Web?Speech?API實(shí)現(xiàn)文字朗讀功能

    在?Vue?頁(yè)面中實(shí)現(xiàn)文字朗讀(Text-to-Speech,TTS)可以通過(guò)瀏覽器的?Web?Speech?API?實(shí)現(xiàn),下面小編就來(lái)和大家簡(jiǎn)單講講具體實(shí)現(xiàn)步驟吧
    2025-02-02
  • vue中使用hover選擇器無(wú)效的問(wèn)題

    vue中使用hover選擇器無(wú)效的問(wèn)題

    這篇文章主要介紹了vue中使用hover選擇器無(wú)效的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • 一文輕松了解v-model及其修飾符

    一文輕松了解v-model及其修飾符

    這篇文章主要給大家介紹了關(guān)于v-model及其修飾符的相關(guān)資料,v-model指令有三個(gè)可以選用的修飾符:.lazy、.number以及.trim,本文通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2021-11-11
  • 使用vant-uploader上傳照片無(wú)法刪除的解決

    使用vant-uploader上傳照片無(wú)法刪除的解決

    這篇文章主要介紹了使用vant-uploader上傳照片無(wú)法刪除的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • 如何解決npm i下載依賴的時(shí)候出現(xiàn)某依賴版本沖突

    如何解決npm i下載依賴的時(shí)候出現(xiàn)某依賴版本沖突

    這篇文章主要介紹了如何解決npm i 下載依賴的時(shí)候出現(xiàn)某依賴版本沖突問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • vue分頁(yè)器組件編寫(xiě)方法詳解

    vue分頁(yè)器組件編寫(xiě)方法詳解

    這篇文章主要為大家詳細(xì)介紹了vue分頁(yè)器組件編寫(xiě)方法,可設(shè)置初始當(dāng)前頁(yè),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-06-06
  • 使用typescript構(gòu)建Vue應(yīng)用的實(shí)現(xiàn)

    使用typescript構(gòu)建Vue應(yīng)用的實(shí)現(xiàn)

    這篇文章主要介紹了使用typescript構(gòu)建Vue應(yīng)用的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • Vue生命周期區(qū)別詳解

    Vue生命周期區(qū)別詳解

    這篇文章主要介紹了Vue生命周期區(qū)別詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-07-07
  • Vue2.0腳手架搭建

    Vue2.0腳手架搭建

    這篇文章介紹了使用vue-cli搭建腳手架的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-03-03
  • vue.js實(shí)現(xiàn)三級(jí)菜單效果

    vue.js實(shí)現(xiàn)三級(jí)菜單效果

    這篇文章主要為大家詳細(xì)介紹了vue.js實(shí)現(xiàn)三級(jí)菜單效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-10-10

最新評(píng)論

佳木斯市| 莲花县| 宁乡县| 阜平县| 中牟县| 拉萨市| 佛冈县| 景宁| 延边| 曲靖市| 乃东县| 沈丘县| 宜都市| 崇左市| 临潭县| 盐津县| 台州市| 武功县| 沈丘县| 藁城市| 昌邑市| 中卫市| 灌云县| 神木县| 泗阳县| 华蓥市| 霍州市| 泗水县| 屯门区| 万山特区| 临江市| 彰化县| 政和县| 元朗区| 常山县| 新密市| 德阳市| 宜兰市| 武清区| 呼玛县| 郸城县|