状态管理及cookie
大约 1 分钟
状态管理及cookie
在Nuxt2中,如果我们要使用cookie,需要引入插件js-cookie,在Nuxt3中,也不再集成Vuex,可以利用Nuxt3的composables自动导入属性,把它们定义在composables目录中,这样他们将成为全局类型安全的状态。
1、useState使用
首先我们需要在项目的根目录新建composables文件夹,然后创建状态管理文件如:composables/state.ts.
//首先引入useState、useCookie
import { useState, useCookie } from "nuxt/app";
export const userLangeages = () => {
const langages = useCookie('lang')
langages.value = langages.value || 'cn'
return useState('userLang', () => langages.value)
}
export const userinfo = () => {
return useState('userLang', () => "这是状态数据查看")
}
如何获取state值和修改state的值
<template>
<div>
<div>{{ userlang }}</div>
<div>{{ userin }}</div>
<button @click="onEventClick()"> 更改状态 </button>
</div>
</template>
<script setup lang="ts">
// 不使用layout布局功能
definePageMeta({
layout: false
})
//获取state的值
const userlang = userLangeages ()
const userin = userinfo ()
const onEventClick = () => {
userlang.value = "ljsdfdfe"
userin.value = "状态已经改变了"
}
</script>
<style scoped></style>
点击之前 点击事件,改变状态
2、useCookie使用
<template>
<h3>你好</h3>
</template>
<script setup lang="ts">
// 获取 Cookie
const Cookies = useCookie('token')
// 设置 Cookie
Cookies.value = Cookies.value || ''
// 删除 Cookie
cookie.value = undefined || null
</script>
<style scoped>
</style>