feat(nuxt3): support init function for useState (#767)

This commit is contained in:
Anthony Fu 2021-10-12 22:28:49 +08:00 committed by GitHub
parent 70c0d8eedb
commit 9f0683079e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 6 deletions

View File

@ -5,8 +5,13 @@ import { useNuxtApp } from '#app'
* 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 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()
return toRef(nuxt.payload.state, key)
const state = toRef(nuxt.payload.state, key)
if (state.value === undefined && init) {
state.value = init()
}
return state
}

View File

@ -15,10 +15,7 @@ const greetings = [
'こんにちは',
'你好'
]
const hello = useState('hello')
if (!hello.value) {
hello.value = greetings[Math.random() * greetings.length | 0]
}
const hello = useState('hello', () => greetings[Math.random() * greetings.length | 0])
</script>
<style scoped>