如何使用 Composition API 创建带词典的翻译器

How to create a translator with dictionaries using Composition API

我正在尝试了解如何使用 Composition API。在这个简单的应用程序中,我试图实现一个具有多个词典的反应式翻译器。基本上,我想做的是单击一个按钮并更改页面上的语言。现在点击它什么都不做。 这是我卡住的地方,请检查 flems.io

index.html

<div id="app">
  <div>Hello: {{ Hello }}</div>
  <div>World: {{ World }}</div>
  <button @click="changeLangButtonClickHandler">Change lang</button>
</div>

App.js

const App = {
  setup () {
    const { dictionary, changeLanguage, language } = useTranslator()
    return { ...dictionary.value, changeLanguage, language }
  },
  methods: {
    changeLangButtonClickHandler () {
      const newLanguage = this.language === 'en' ? 'ru' : 'en'
      this.changeLanguage(newLanguage)
    }
  }
}

Vue.createApp(App).mount('#app')

translator.js

const language = Vue.ref('en')
const dictionaries = Vue.ref({
  ru: {
    Hello: 'Привет',
    World: 'Мир'
  },
  en: {
    Hello: 'Hello',
    World: 'World'
  }
})

function useTranslator () {
  const dictionary = Vue.computed(() => {
    return dictionaries.value[language.value]
  })
  function changeLanguage (lang) {
    language.value = lang
  }
  return { dictionary, changeLanguage, language }
}

这是一个 working 版本。

我在 index.html

中用 <div>Hello: {{ dictionary.Hello }}</div> 替换了 <div>Hello: {{ Hello }}</div>

并且还在 setup 函数中用 return { dictionary, changeLanguage, language } 替换了 { ...dictionary.value, changeLanguage, language }

这个问题与反应系统的工作原理有关

问题是,如果您使用 return { ...dictionary.value, changeLanguage, language }...dictionary.value 将停止响应。这就是切换到 ...dictionarydistionary.Hello 的原因。


旁注...,您甚至不需要 useTranslator 函数,您可以像这样导出函数和变量

// private
const dictionaries = Vue.ref({
  ru: {
    Hello: "Привет",
    World: "Мир"
  },
  en: {
    Hello: "Hello",
    World: "World"
  }
});
// public
export const language = Vue.ref("en");
export const dictionary = Vue.computed(() => {
  return dictionaries.value[language.value];
});
export const changeLanguage = lang => {
  language.value = lang;
};

如果您想将组件的各个方面或变量传递给函数,useSomethingSomething() 函数很有用。或者有风格偏好。