https://blog.csdn.net/qq_37473645/article/details/83176633 (opens new window)

 <div class="btn" @click="login()">登陆</div>
  created() {
     const local = this.getCheckCookie()
       if (local === 'true') {
         this.checked = true
       }
  },
// 页面加载调用获取cookie值
  mounted() {
    this.getCookie();
  },
  methods: {
    login() {
    //校验输入是否为空或格式是否正确
    ...
         // 判断复选框是否被勾选 勾选则调用配置cookie方法
               if (this.checked == true) {
                 // 传入账号,密码 和保存天数 3个参数
                 this.setCookie(this.loginForm.username, this.loginForm.password, 7)
               } else {
                 this.clearCookie()
               }
          this.setCheckCookie(this.checked, 7)
      // ajax请求
      console.log('登录成功');
    },

    // 设置cookie
    setCookie(c_name, c_pwd, exdays) {
      const exdate = new Date();
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays);
      window.document.cookie = `${'account' + '='}${c_name};path=/;expires=${exdate.toGMTString()}`;
      window.document.cookie = `${'pwd' + '='}${c_pwd};path=/;expires=${exdate.toGMTString()}`;
    },
  // 设置记住密码 cookie
    setCheckCookie(check, exdays) {
      const exdate = new Date()// 获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 1000 * exdays) // 保存的天数
      // 字符串拼接cookie
      window.document.cookie = `check=${check};path=/;expries=${exdate.toGMTString()}`
    },
  // 读取记住密码cookie
    getCheckCookie() {
      let check = ''
      if (document.cookie.length > 0) {
        const arr = document.cookie.split(';')
        arr.forEach((item) => {
          const arr2 = item.split('=')
          if (arr2[0].trim() == 'check') {
          
            check = arr2[1].trim()
          }
        })
      }
      return check
    },
     // 读取cookie
       getCookie() {
         if (document.cookie.length > 0) {
           const arr = document.cookie.split(';')
           for (let i = 0; i < arr.length; i++) {
             const arr2 = arr[i].split('=') // 再次切割
             // 判断寻找对应的值
             if (arr2[0].trim() == 'name') { // 去除空格
               this.loginForm.username = arr2[1]
             } else if (arr2[0].trim() == 'password') {
               this.loginForm.password = arr2[1]
             }
           }
         }
       },

  // 清除cookie
    clearCookie() {
      this.setCookie('', '', -1)
      this.setCheckCookie('', -1)
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
lastUpdate: 5/13/2021, 5:35:14 PM