mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-22 05:35:13 +00:00
feat(nuxt3): support init function for useState
(#767)
This commit is contained in:
parent
70c0d8eedb
commit
9f0683079e
@ -5,8 +5,13 @@ import { useNuxtApp } from '#app'
|
|||||||
* Create a global reactive ref that will be hydrated but not shared across ssr requests
|
* Create a global reactive ref that will be hydrated but not shared across ssr requests
|
||||||
*
|
*
|
||||||
* @param key a unique key to identify the data in the Nuxt payload
|
* @param key a unique key to identify the data in the Nuxt payload
|
||||||
|
* @param init a function that provides initial value for state if it's not initiated
|
||||||
*/
|
*/
|
||||||
export const useState = <T> (key: string): Ref<T> => {
|
export const useState = <T> (key: string, init?: (() => T)): Ref<T> => {
|
||||||
const nuxt = useNuxtApp()
|
const nuxt = useNuxtApp()
|
||||||
return toRef(nuxt.payload.state, key)
|
const state = toRef(nuxt.payload.state, key)
|
||||||
|
if (state.value === undefined && init) {
|
||||||
|
state.value = init()
|
||||||
|
}
|
||||||
|
return state
|
||||||
}
|
}
|
||||||
|
@ -15,10 +15,7 @@ const greetings = [
|
|||||||
'こんにちは',
|
'こんにちは',
|
||||||
'你好'
|
'你好'
|
||||||
]
|
]
|
||||||
const hello = useState('hello')
|
const hello = useState('hello', () => greetings[Math.random() * greetings.length | 0])
|
||||||
if (!hello.value) {
|
|
||||||
hello.value = greetings[Math.random() * greetings.length | 0]
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
Loading…
Reference in New Issue
Block a user