lemooljiang avatar

状态管理和cookie / nuxt#10

lemooljiang

Published: 05 Jul 2023 › Updated: 05 Jul 2023状态管理和cookie  / nuxt#10

状态管理和cookie / nuxt#10

状态管理 useState

useState用于创建响应式的且服务端友好的跨组件状态,类似于Vue中的state的功能。

const counter = useState('counter', () => Math.round(Math.random() * 1000))
counter++
counter.value = 20 //重新赋值

const user = useState('user', () => {
  return {
    token: token.value,
    user: userObj.value
 }
})

//composables/useState.ts
export const useCounter = () => useState<number>('counter', () => 0)
export const useColor = () => useState<string>('color', () => 'pink')

<script setup>
const color = useColor() // Same as useState('color')
</script>

useCookie

在页面中,组件和插件可以使用useCookie,一个SSR友好的组合来读写cookies。
在composables中是不能使用 useCookie 的!因为composables是先在服务器端渲染的,是读取不到客户端中的cookie!

const cookie = useCookie(name, options)
eg:
const counter = useCookie('counter', { maxAge: 60 }) //60秒
counter.value = {
  name: "hello",
  age: 37
}
const token = useCookie('token', {maxAge: 60 * 5})
token.value = "hello world"

// 获取
const s = useCookie('counter')
s.value

//删除
s.value = null
const token = useCookie("token")
token.value = null

const s = useCookie('counter')
const removeCookie = () => {
    s.value = null
    console.log(256,s)
}

// 将用户登录成功返回的token存储在cookie当中,用户登录成功的标识
const token = useCookie("token")
token.value = data.value.token
const user = useUser()
user.value = data.value

//判断token是否有值
const token = useCookie("token")
token.value == undefined  //无值
 token.value == null
 !token.value  //无值则为true

Leave 状态管理和cookie / nuxt#10 to:

Written by

Designer , Poet , Technology enthusiasts

Read more #cn posts


Best Posts From lemooljiang

We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From lemooljiang