<span id="mktg5"></span>

<i id="mktg5"><meter id="mktg5"></meter></i>

        <label id="mktg5"><meter id="mktg5"></meter></label>
        最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
        問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
        當前位置: 首頁 - 科技 - 知識百科 - 正文

        在Vue中如何使用Cookie操作實例

        來源:懂視網 責編:小采 時間:2020-11-27 22:34:04
        文檔

        在Vue中如何使用Cookie操作實例

        在Vue中如何使用Cookie操作實例:大家好,由于公司忙著趕項目,導致有段時間沒有發布新文章了。今天我想跟大家談談Cookie的使用。同樣,這個Cookie的使用方法是我從公司的項目中抽出來的,為了能讓大家看懂,我會盡量寫詳細點。廢話少說,我們直接進入正題。 一、安裝Cookie 在Vue2.
        推薦度:
        導讀在Vue中如何使用Cookie操作實例:大家好,由于公司忙著趕項目,導致有段時間沒有發布新文章了。今天我想跟大家談談Cookie的使用。同樣,這個Cookie的使用方法是我從公司的項目中抽出來的,為了能讓大家看懂,我會盡量寫詳細點。廢話少說,我們直接進入正題。 一、安裝Cookie 在Vue2.

        大家好,由于公司忙著趕項目,導致有段時間沒有發布新文章了。今天我想跟大家談談Cookie的使用。同樣,這個Cookie的使用方法是我從公司的項目中抽出來的,為了能讓大家看懂,我會盡量寫詳細點。廢話少說,我們直接進入正題。

        一、安裝Cookie

        在Vue2.0下,這個貌似已經不需要安裝了。因為當你創建一個項目的時候,npm install 已經為我們安裝好了。我的安裝方式如下:

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

        這是我創建好的目錄結構,大家可以看一下:


        項目結構

        二、封裝Cookie方法

        在util文件夾下,我們創建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;
        }
        
        //設置cookie,增加到vue實例方便全局調用
        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傳到后臺

        關于這點,我需要說明一下,我們這里使用的是axios進行HTTP傳輸數據,為了更好的使用axios,我們在util文件夾下創建http.js文件,然后封裝GET,POST等方法,代碼如下:

        import axios from 'axios' //引用axios
        import {getCookie} from './util' //引用剛才我們創建的util.js文件,并使用getCookie方法
        
        // axios 配置
        axios.defaults.timeout = 5000; 
        axios.defaults.baseURL = 'http://localhost/pjm-shield-api/public/v1/'; //這是調用數據接口
        
        // http request 攔截器,通過這個,我們就可以把Cookie傳到后臺
        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' //設置跨域頭部
         };
         if (token) {
         config.params = {'token': token} //后臺接收的參數,后面我們將說明后臺如何接收
         }
         return config;
         },
         err => {
         return Promise.reject(err);
         }
        );
        
        
        // http response 攔截器
        axios.interceptors.response.use(
         response => {
        //response.data.errCode是我接口返回的值,如果值為2,說明Cookie丟失,然后跳轉到登錄頁,這里根據大家自己的情況來設定
         if(response.data.errCode == 2) {
         router.push({
         path: '/login',
         query: {redirect: router.currentRoute.fullPath} //從哪個頁面跳轉
         })
         }
         return response;
         },
         error => {
         return Promise.reject(error.response.data)
         });
        
        export default axios;
        
        /**
         * fetch 請求方法
         * @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 請求方法
         * @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布局,對應不熟悉Element-ui的朋友們,可以去惡補一下。后面我們將講解如何使用它進行布局。登錄組件的代碼如下:

        <template>
         <el-form ref="AccountFrom" :model="account" :rules="rules" label-position="left" label-width="0px"
         class="demo-ruleForm login-container">
         <h3 class="title">后臺管理系統</h3>
         <el-form-item prop="u_telephone">
         <el-input type="text" v-model="account.u_telephone" auto-complete="off" placeholder="請輸入賬號"></el-input>
         </el-form-item>
         <el-form-item prod="u_password">
         <el-input type="password" v-model="account.u_password" auto-complete="off" placeholder="請輸入密碼"></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:''
         },
         //表單驗證規則
         rules: {
         u_telephone: [
         {required: true, message:'請輸入賬號',trigger: 'blur'}
         ],
         u_password: [
         {required: true,message:'請輸入密碼',trigger: 'blur'}
         ]
         }
         }
         },
         mounted() {
         //初始化
         },
         methods: {
         handleLogin() {
         this.$refs.AccountFrom.validate((valid) => {
         if(valid) {
         this.logining = true;
        //其中 'm/login' 為調用的接口,this.account為參數
         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); //設置Session
         this.setCookie('u_uuid',res.errData.u_uuid,expireDays); //設置用戶編號
         if(this.$route.query.redirect) {
         this.$router.push(this.$route.query.redirect);
         } else {
         this.$router.push('/home'); //跳轉用戶中心頁
         }
         }
         });
         } else {
         console.log('error submit');
         return false;
         }
         });
         }
         }
         }
        </script>
        
        

        五、在路由中驗證token存不存在,不存在的話會到登錄頁

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

        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' //首頁
        import Home from '@/views/index/Home' //主頁
        import right from '@/components/UserRight' //右側
        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' //個人信息
        import editpwd from '@/views/user/EditPwd' //修改密碼
        
        Vue.use(Router);
        
        const routes = [
         {
         path: '/',
         name:'登錄',
         component:Index
         },
         {
         path: '/',
         name: 'home',
         component: Home,
         redirect: '/home',
         leaf: true, //只有一個節點
         menuShow: true,
         iconCls: 'iconfont icon-home', //圖標樣式
         children: [
         {path:'/home', component: right, name: '首頁', 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: '用戶認證審核', 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: '票據管理',
         menuShow: true,
         iconCls: 'iconfont icon-books',
         children: [
         {path: '/bill/list', component: billlist, name: '已開票據列表', menuShow: true, meta:{requireAuth: true }},
         {path: '/bill/info', component: billinfo, name: '票據詳細頁', menuShow: false, meta:{requireAuth: true }},
         {path: '/bill/add', component: addbill, name: '新建開票信息', menuShow: true, meta:{requireAuth: true }}
        
         ]
         },
         {
         path: '/',
         component: Home,
         name: '系統設置',
         menuShow: true,
         iconCls: 'iconfont icon-setting1',
         children: [
         {path: '/userinfo', component: userinfo, name: '個人信息', menuShow: true, meta:{requireAuth: true }},
         {path: '/editpwd', component: editpwd, name: '修改密碼', menuShow: true, meta:{requireAuth: true }}
         ]
         }
         ];
        
        const router = new Router({
         routes
        });
        
        

        備注:請注意路由中的 meta:{requireAuth: true },這個配置,主要為下面的驗證做服務。

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

        如果存在,就繼續執行下面的操作,如果不存在,就刪除客戶端的Cookie,同時頁面跳轉到登錄頁,代碼如下。

        //這個是請求頁面路由的時候會驗證token存不存在,不存在的話會到登錄頁
        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;


        聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

        文檔

        在Vue中如何使用Cookie操作實例

        在Vue中如何使用Cookie操作實例:大家好,由于公司忙著趕項目,導致有段時間沒有發布新文章了。今天我想跟大家談談Cookie的使用。同樣,這個Cookie的使用方法是我從公司的項目中抽出來的,為了能讓大家看懂,我會盡量寫詳細點。廢話少說,我們直接進入正題。 一、安裝Cookie 在Vue2.
        推薦度:
        標簽: 如何使用 操作 VUE
        • 熱門焦點

        最新推薦

        猜你喜歡

        熱門推薦

        專題
        Top
        主站蜘蛛池模板: 免费黄网站在线看| 两个人看的www免费| 成人男女网18免费视频| 亚洲网红精品大秀在线观看| 久久精品视频免费| 香蕉蕉亚亚洲aav综合| 永久免费av无码网站yy| 亚洲精品自产拍在线观看| a毛片在线还看免费网站| 亚洲成在人线av| 久久久久久一品道精品免费看| 亚洲视频在线观看地址| 日韩免费人妻AV无码专区蜜桃| 亚洲精选在线观看| 免费观看无遮挡www的视频| 亚洲人成77777在线播放网站不卡 亚洲人成77777在线观看网 | 亚洲一区二区三区精品视频| 成人女人A级毛片免费软件| 亚洲一区欧洲一区| 亚洲国产成人久久一区WWW| 国产精品免费在线播放| 亚洲高清视频免费| 噜噜嘿在线视频免费观看| 乱淫片免费影院观看| 亚洲AV日韩精品久久久久久| 五月婷婷综合免费| 免费人成又黄又爽的视频在线电影 | 一级做a爰片久久毛片免费看 | 免费国产a国产片高清| 97在线免费观看视频| 亚洲视频中文字幕在线| 午夜无遮挡羞羞漫画免费| 国产免费高清69式视频在线观看| 久久久亚洲精品国产| 日韩成人在线免费视频| 久久亚洲精品无码AV红樱桃| 亚洲一区二区无码偷拍| 国产AV无码专区亚洲AWWW| 噼里啪啦免费观看高清动漫4| 免费无码专区毛片高潮喷水| 老司机亚洲精品影院|