Skip to content

Language Switching

Because the TechUI multi-language system utilizes an asynchronous on-demand loading strategy, hot-swapping is not supported to ensure resources are loaded correctly. The standard process for switching languages is: Lock Preference -> Refresh Page.

Core Implementation

The following is a minimal example of a language switching component, demonstrating how to use lockLang and location.reload to complete the switch.

html
<script setup>
import { inject, reactive, onMounted } from 'vue';
import { lockLang } from "@techui/utils"; // 1. Import the locking tool

const { getSysLang } = inject('$global');

const state = reactive({
  currentLang: 'cn',
  options: [
    { label: "Simplified Chinese", value: "cn" },
    { label: "English", value: "en" }
  ]
});

onMounted(() => {
  // 2. Initialize and display the current language
  state.currentLang = getSysLang();
});

const changeLang = (val) => {
  if(state.currentLang === val) return;
  
  // 3. Core steps: Write to local storage and refresh
  lockLang(val); 
  
  // Brief delay is suggested to optimize user experience
  setTimeout(() => location.reload(), 300);
}
</script>

<template>
  <div class="lang-switch">
    <button 
      v-for="item in state.options" 
      :key="item.value"
      @click="changeLang(item.value)"
      :class="{ active: state.currentLang === item.value }"
    >
      {{ item.label }}
    </button>
  </div>
</template>

Logic Analysis

  1. lockLang(val): This is the key to switching. It persistently writes the target language code (e.g., 'en') into the browser's LocalStorage.
  2. location.reload(): This forces a browser refresh. When the page reloads, TechUI's initialization function initI18n prioritizes reading the configuration from LocalStorage, thereby loading the corresponding language package.

Released under the MIT License.