vue中保存和獲取cookie,讀寫cookie以及設置有效時間等,使用js-cookie


  1. NPM 安裝
npm install js-cookie --save
復制代碼
  1. 引入
import Cookies from 'js-cookie' 復制代碼
  1. 設置cookie,創建一個cookie,在整個站點有效:
cookies.set('name','value') 復制代碼

或 創建一個過期的cookie,該cookie對當前頁的路徑有效:

cookies.set('name','value',{expires:7,path:'})
復制代碼
  1. 獲取cookie:
cookies.get('name');//=>'值' 復制代碼
  1. 讀取所有可見的Cookie:
cookies.get();//=>{name:'value'} 復制代碼
  1. 刪除Cookie:
cookies.remove('name'); 復制代碼
  1. 刪除對當前頁路徑有效的cookie:
cookies.set('name','value',{path:'});

cookies.remove('name');//失敗!

cookies.remove('name',{path:'});//remove!
復制代碼

Forexample:

<template>
    <div class="login-wrap">
        <div class="ms-login">
            <div class="ms-title">后台管理系統</div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="ms-content">
                <el-form-item prop="username">
                    <el-input v-model="ruleForm.username" placeholder="請輸入用戶名">
                        <el-button slot="prepend" icon="el-icon-lx-people"></el-button>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input type="password" placeholder="請輸入密碼" v-model="ruleForm.password"
                              @keyup.enter.native="submitForm('ruleForm')">
                        <el-button slot="prepend" icon="el-icon-lx-lock"></el-button>
                    </el-input>
                </el-form-item>
                <div class="login-btn">
                    <el-button type="primary" @click="submitForm('ruleForm')">登錄</el-button>
                </div>
               
            </el-form>
        </div>
    </div>
</template>
復制代碼
<script>
    export default {
        data: function () {
            return {
                ruleForm: {
                    username: '',
                    password: ''
                },
                rules: {
                    username: [
                        {required: true, message: '請輸入用戶名', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '請輸入密碼', trigger: 'blur'}
                    ]
                }
            }
        },
				 //頁面加載調用獲取cookie值
				mounted() {
						this.getCookie();
				},
        methods: {
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$axios.post('admin/login',this.$qs.stringify(this.ruleForm))
												.then((res) => {
                            console.log(res);
                            if (res.data.code == 0) {
                                localStorage.setItem('ms_username', this.ruleForm.username);
																//保存用戶名和密碼到cookie
																this.setCookie(this.ruleForm.username,this.ruleForm.password,7);
																//跳轉
                                this.$router.push('/');
																this.$message.success(res.data.message);
                            } else {
                                console.log(res.data.message);
                                this.$message.warning(res.data.message);
                            }
                        }).catch((res) => {
                            console.log(res);
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
						 //設置cookie
            setCookie(c_name, c_pwd, exdays) {
                var exdate = new Date(); //獲取時間
                exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天數
                //字符串拼接cookie
                window.document.cookie = "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
                window.document.cookie = "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
            },
            //讀取cookie
            getCookie: function() {
                if (document.cookie.length > 0) {
                    var arr = document.cookie.split('; '); //這里顯示的格式需要切割一下自己可輸出看下
                    for (var i = 0; i < arr.length; i++) {
                        var arr2 = arr[i].split('='); //再次切割
                        //判斷查找相對應的值
                        if (arr2[0] == 'userName') {
                            this.ruleForm.username = arr2[1]; //保存到保存數據的地方
                        } else if (arr2[0] == 'userPwd') {
                            this.ruleForm.password = arr2[1];
                        }
                    }
                }
            },
        }
    }
</script>

作者:Elvira411
鏈接:https://juejin.im/post/5dba3783e51d4529e009fece
來源:掘金
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM