Home > Web Front-end > Vue.js > body text

How to use cookies in vue3

PHPz
Release: 2023-05-12 14:19:27
forward
3402 people have browsed it

Preface

The most commonly used place for cookies is to save the user's account and password, which can avoid the user having to re-enter every time they log in

1.Installation of cookies in vue

Enter the command npm install vue-cookies --save in the terminal to install cookies. After installation, write the following code in the main.js file

import { createApp } from 'vue'
import VueCookies from 'vue-cookies'
 
const app = createApp(App)
 
app.config.globalProperties.$cookies = VueCookies
Copy after login

Using cookies in the project

2. Setting cookies during the login process

Because users may change their passwords, my common approach in business is to wait until the login interface returns correct data. (The judgment is correct, you can log in) First determine whether there are cookies, delete them if they are, and then create new cookies. The code is as follows

if (ret.code === 200) {
  // 删除之前的cookies
  if($cookies.isKey("xxxxx") ){
     $cookies.remove("xxxxx")
  }
}
Copy after login

Then re-store the login information in the cookie, the code is as follows

// 设置cookies保存的内容
const xxxxx = {
  username: '',
  password: '',
  // 以下还有很多信息
}
Copy after login

The last step is to re-save the cookies, the code is as follows

// 设置cookies的日期为一个月
$cookies.config("1m")
// 设置cookies
$cookies.set("xxxxx",xxxxx); // 前面的为设置cookies的名字,后面为内容
Copy after login

I suddenly thought of a question often mentioned in interviews, how to set cookies to be invalid, the answer is to set the expiration time of cookies to before time, I don’t know if you have thought of it.

3. Get the previously stored cookies where you need them

The code is also very simple

import { getCurrentInstance } from 'vue'
 
// 创建可以访问内部组件实例的实例
const internalInstance = getCurrentInstance()
const internalData = internalInstance.appContext.config.globalProperties
const xxxxx = internalData.$cookies.get('xxxxx') // 后面的为之前设置的cookies的名字
Copy after login

This way you can get the contents of the cookies where you need them .

The above is the detailed content of How to use cookies in vue3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template