问题描述
我正在尝试了解如何使用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,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,language }
}
解决方法
问题在于,如果您使用的是return { ...dictionary.value,changeLanguage,language }
,则...dictionary.value
将停止响应。这就是为什么切换到...dictionary
和distionary.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()
函数将很有帮助。或有样式偏好。
这是working版。
我在<div>Hello: {{ Hello }}</div>
中用<div>Hello: {{ dictionary.Hello }}</div>
替换了index.html
并在{ ...dictionary.value,language }
函数中用return { dictionary,language }
替换了setup
问题与反应系统的工作原理有关