How to use cookies in Vue to operate instances and vuecookie to operate instances

Source: Internet
Author: User

How to use cookies in Vue to operate instances and vuecookie to operate instances

Hello everyone, the company is busy with projects, so it has not published any new articles for some time. Today, I want to talk about how to use cookies. Similarly, the use of this Cookie is extracted from the company's projects. In order to make everyone understand it, I will try to write details as much as possible. Let's get started with the topic.

1. Install cookies

In Vue2.0, it seems that no installation is required. Because npm install has been installed for us when you create a project. My installation method is as follows:

# Global installation of vue-cli $ npm install -- global vue-cli # create a new project based on the webpack template $ vue init webpack my-project # install dependencies, walk you $ cd my-project $ npm install

Here is the directory structure I created. You can take a look at it:


Project Structure

Ii. Cookie Encapsulation Method

In the util folder, create the util. js file and run the code

// Obtain cookie, export function getCookie (name) {var arr, reg = new RegExp ("(^ |)" + name + "= ([^;] *) (; | $) "); if (arr = document. cookie. match (reg) return (arr [2]); else return null;} // set the cookie and add it to the vue instance to call the export function setCookie (c_name, value, expiredays) globally) {var exdate = new Date (); exdate. setDate (exdate. getDate () + expiredays); document. cookie = c_name + "=" + escape (value) + (expiredays = null )? "": "; Expires =" + exdate. toGMTString () ;}; // Delete cookieexport 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 ();};

3. Upload the Cookie to the background in HTTP

For more information, see axios for HTTP data transmission. To better use axios, create http in the util folder. js file, and then encapsulate methods such as GET and POST. The Code is as follows:

Import axios from 'axios '// reference axiosimport {getCookie} from '. /util '// reference the util we just created. js file, and use the getCookie method // axios to configure axios. defaults. timeout = 5000; axios. defaults. baseURL = 'HTTP: // localhost/pjm-shield-api/public/v1/'; // This is the call data interface // http request interceptor, we can upload the Cookie to axios in the background. interceptors. request. use (config => {const token = getCookie ('session '); // obtain the Cookie config. data = JSON. stringify (config. data); config. headers = {'content-type': 'application/x-www-form-urlencoded' // sets the cross-origin header}; if (token) {config. params = {'Token': token} // The parameter received by the background. The following describes how to receive the parameter} return config ;}, err =>{ return Promise. reject (err) ;}); // http response interceptor axios. interceptors. response. use (response => {// response. data. errCode is the value returned by my interface. if the value is 2, it indicates that the Cookie is lost and then jumps to the logon page. Here, we will set if (response. data. errCode = 2) {router. push ({path: '/login', query: {redirect: router. currentRoute. fullPath} // from which page to jump})} return response ;}, error =>{ return Promise. reject (error. response. data)}); export default axios;/*** fetch Request Method * @ 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 Request Method * @ 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 method encapsulation * @ 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 method encapsulate * @ 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 );})})}

4. Use cookies in the login component

Because I use the Element-ui layout for logging on to the component, it can be supplemented by an unfamiliar Element-ui. Later we will explain how to use it for layout. The logon component code is as follows:

<Template> <el-form ref = "AccountFrom": model = "account ": rules = "rules" label-position = "left" label-width = "0px" class = "demo-ruleForm login-container"> 

5. Verify that the token does not exist in the route. If it does not exist, it will go to the logon page.

Set the route in router -- index. js. The Code is as follows:

Import Vue from 'vue 'import Router from 'vue-router' import {post, fetch, patch, put} from '@/util/http' import {delCookie, getCookie} from '@/util' import Index from '@/views/index/Index' // Home page import Home from' @/views/Index/home' // Home Page import right from '@/components/userright' // import userlist from' @/views/user/userlist' // user list import usercert from '@/views/user/Certification '// user audit import userlook from' @/views/user/UserLook '// user view import usercertlook from' @/views/user/UserCertLook '// user audit view 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 '// personal information import editpwd from '@/views/user/editpwd' // change the password Vue. use (Router); const routes = [{path: '/', name: 'login', component: Index}, {path: '/', name: 'home ', component: Home, redirect: '/home', leaf: true, // only one node menuShow: true, iconCls: 'iconfont icon-home', // The icon style children: [{path: '/home', component: right, name: 'homepage', menuShow: true, meta: {requireAuth: true}]}, {path: '/', component: Home, name: 'user management', menuShow: true, iconCls: 'iconfont icon-users', children: [{path: '/userlist ', component: userlist, name: 'user list', menuShow: true, meta: {requireAuth: true },{ path: '/usercert', component: usercert, name: 'User authentication Review', menuShow: true, meta: {requireAuth: true },{ path: '/userlook', component: userlook, name: 'view user information ', menuShow: false, meta: {requireAuth: true },{ path: '/usercertlook', component: usercertlook, name: 'user review information', menuShow: false, meta: {requireAuth: true }},]}, {path: '/', component: Home, name: 'information', menuShow: true, iconCls: 'iconfont icon-Book', children: [{path: '/sellbill', component: sellbill, name: 'ticket seller information', menuShow: true, meta: {requireAuth: true }}, {path: '/buybill', component: buybill, name: 'ticket information', menuShow: true, meta: {requireAuth: true },{ path: '/changebill', component: changebill, name: 'ticket exchange information', menuShow: true, meta: {requireAuth: true },{ path:'/bill/editsellbill ', component: editsellbill, name: 'edit ticket selling information', menuShow: false, meta: {requireAuth: true}] },{ path: '/bill', component: Home, name: 'ticket management', menuShow: true, iconCls: 'iconfont icon-Book', children: [{path: '/bill/list', component: billlist, name: 'ticket opened list', menuShow: true, meta: {requireAuth: true },{ path: '/bill/info', component: billinfo, name: 'ticket details page', menuShow: false, meta: {requireAuth: true },{ path: '/bill/add', component: addbill, name: 'New invoicing information', menuShow: true, meta: {requireAuth: true}]}, {path: '/', component: Home, name: 'System settings ', menuShow: true, iconCls: 'iconfont icon-setting1 ', children: [{path:'/userinfo', component: userinfo, name: 'info', menuShow: true, meta: {requireAuth: true },{ path: '/editpwd', component: editpwd, name: 'change password', menuShow: true, meta: {requireAuth: true}]; const router = new Router ({routes });

Note: Pay attention to the meta: {requireAuth: true} in the route. This configuration mainly serves the following verification.

If (to. meta. requireAuth), this Code indicates that if requireAuth: true, it determines whether the user exists.

If the Cookie exists, perform the following operations. If the Cookie does not exist, delete the Cookie from the client and go to the logon page. The Code is as follows.

// This indicates that the token does not exist when the request page is routed. If the token does not exist, it will go to the logon page router. beforeEach (to, from, next) => {if (. 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;


These are the usage of cookies in the project. We hope they will be helpful for your learning and support the customer's home.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.