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
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
Using cookies in the project
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") } }
Then re-store the login information in the cookie, the code is as follows
// 设置cookies保存的内容 const xxxxx = { username: '', password: '', // 以下还有很多信息 }
The last step is to re-save the cookies, the code is as follows
// 设置cookies的日期为一个月 $cookies.config("1m") // 设置cookies $cookies.set("xxxxx",xxxxx); // 前面的为设置cookies的名字,后面为内容
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.
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的名字
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!