I am in the process of creating a bilingual blog using Nuxt.js and TypeScript. This application interacts with a REST API to retrieve data that is structured like this:
{
"Headline_de": "Mein erster Blogpost",
"Headline_en": "My first Blogpost"
}
Retrieving data for one language from the API looks like this:
export const mutations = {
setCurrentBlogpost(state, blogpostId) {
const currentBlogpost = await axios.get(api + blogpostId);
const normalizedBlogpost = {
headline: currentBlogpost.Headline_de
};
state.commit('setCurrentBlogpost', currentBlogpost.data);
}
};
Now I want to fetch the data based on the currently selected language. I attempted to manipulate the property like so:
const headline = 'currentBlogpost.Headline_' + this.$i18n.locale; // outputs de or en
export const mutations = {
setCurrentBlogpost(state, currentBlogpost) {
const normalizedBlogpost = {
headline: headline
};
state.currentBlogpost = normalizedBlogpost;
}
};
However, this approach only sets the property as a string. Is there a method to manipulate the input properties to address this issue?
Edit: I managed to make it work using this method. But I believe there might be a simpler solution.
setCurrentBlogpost(state, currentBlogpost) {
if (this.$i18n.locale == 'de') {
const normalizedBlogpost: Blogpost = {
headline: currentBlogpost.Headline_de
};
state.currentBlogpost = normalizedBlogpost;
}
if (this.$i18n.locale == 'en') {
const normalizedBlogpost: Blogpost = {
headline: currentBlogpost.Headline_en
};
state.currentBlogpost = normalizedBlogpost;
}
}