docs: add advanced usage example of useState (#20249)

This commit is contained in:
Luciano Tonet 2023-05-20 19:31:22 -03:00 committed by GitHub
parent 980728275a
commit e847e33a75
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -59,10 +59,71 @@ const counter = useState('counter', () => Math.round(Math.random() * 1000))
::ReadMore{link="/docs/api/composables/use-state"}
::
### Advanced
### Advanced Usage
In this example, we use a composable that detects the user's default locale from the HTTP request headers and keeps it in a `locale` state.
```ts [composables/locale.ts]
import type { Ref } from 'vue'
export const useLocale = () => useState<string>('locale', () => useDefaultLocale().value)
export const useDefaultLocale = (fallback = 'en-US') => {
const locale = ref(fallback)
if (process.server) {
const reqLocale = useRequestHeaders()['accept-language']?.split(',')[0]
if (reqLocale) {
locale.value = reqLocale
}
} else if (process.client) {
const navLang = navigator.language
if (navLang) {
locale.value = navLang
}
}
return locale
}
export const useLocales = () => {
const locale = useLocale()
const locales = ref([
'en-US',
'en-GB',
...
'ja-JP-u-ca-japanese'
])
if (!locales.value.includes(locale.value)) {
locales.value.unshift(locale.value)
}
return locales
}
export const useLocaleDate = (date: Ref<Date> | Date, locale = useLocale()) => {
return computed(() => new Intl.DateTimeFormat(locale.value, { dateStyle: 'full' }).format(unref(date)))
}
```
```vue [app.vue]
<script setup>
const locales = useLocales()
const locale = useLocale()
const date = useLocaleDate(new Date('2016-10-26'))
</script>
<template>
<div>
<h1>Nuxt birthday</h1>
<p>{{ date }}</p>
<label for="locale-chooser">Preview a different locale</label>
<select id="locale-chooser" v-model="locale">
<option v-for="locale of locales" :key="locale" :value="locale">
{{ locale }}
</option>
</select>
</div>
</template>
```
::LinkExample{link="/docs/examples/other/locale"}
::