|
11 | 11 | </div> |
12 | 12 | <form class="language"> |
13 | 13 | <label>{{ t('labels.language') }}</label> |
14 | | - <select v-model="locale"> |
15 | | - <option value="en">en</option> |
16 | | - <option value="ja">ja</option> |
| 14 | + <select v-model="currentLocale"> |
| 15 | + <option |
| 16 | + v-for="optionLocale in supportLocales" |
| 17 | + :key="optionLocale" |
| 18 | + :value="optionLocale" |
| 19 | + > |
| 20 | + {{ optionLocale }} |
| 21 | + </option> |
17 | 22 | </select> |
18 | 23 | </form> |
19 | 24 | </nav> |
20 | 25 | <router-view /> |
21 | 26 | </template> |
22 | 27 |
|
23 | 28 | <script> |
24 | | -import { ref, watch, defineComponent } from 'vue' |
25 | | -import { useRoute, useRouter } from 'vue-router' |
| 29 | +import { defineComponent, watch, ref } from 'vue' |
| 30 | +import { useRouter } from 'vue-router' |
26 | 31 | import { useI18n } from 'vue-i18n' |
| 32 | +import { SUPPORT_LOCALES } from './i18n' |
27 | 33 |
|
28 | 34 | export default defineComponent({ |
29 | 35 | name: 'App', |
30 | 36 | setup() { |
31 | | - const { t, locale } = useI18n() |
32 | 37 | const router = useRouter() |
33 | | - const route = useRoute() |
| 38 | + const { t, locale } = useI18n({ useScope: 'global' }) |
34 | 39 |
|
35 | | - // when change the locale, go to locale route |
36 | | - watch(locale, val => { |
| 40 | + /** |
| 41 | + * select locale value for language select form |
| 42 | + * |
| 43 | + * If you use the vue-i18n composer `locale` property directly, it will be re-rendering component when this property is changed, |
| 44 | + * before dynamic import was used to asynchronously load and apply locale messages |
| 45 | + * To avoid this, use the anoter locale reactive value. |
| 46 | + */ |
| 47 | + const currentLocale = ref(locale.value) |
| 48 | +
|
| 49 | + // sync to switch locale from router locale path |
| 50 | + watch(router.currentRoute, route => { |
| 51 | + currentLocale.value = route.params.locale |
| 52 | + }) |
| 53 | +
|
| 54 | + /** |
| 55 | + * when change the locale, go to locale route |
| 56 | + * |
| 57 | + * when the changes are detected, load the locale message and set the language via vue-router navigation guard. |
| 58 | + * change the vue-i18n locale too. |
| 59 | + */ |
| 60 | + watch(currentLocale, val => { |
37 | 61 | router.push({ |
38 | | - name: route.name, |
| 62 | + name: router.currentRoute.value.name, |
39 | 63 | params: { locale: val } |
40 | 64 | }) |
41 | 65 | }) |
42 | 66 |
|
43 | | - return { t, locale } |
| 67 | + return { t, locale, currentLocale, supportLocales: SUPPORT_LOCALES } |
44 | 68 | } |
45 | 69 | }) |
46 | 70 | </script> |
|
0 commit comments