I'm building an Nuxt.js billingual Blog with TypeScript. The application consumes data from an REST API. The data is structured like this:
{
"Headline_de": "Mein erster Blogpost",
"Headline_en": "My first Blogpost",
}
Getting the data from the API for one language 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 get the data, depending on which language currently is chosen. I already tried to manipulate the property like this:
const headline = 'currentBlogpost.Headline_' + this.$i18n.locale; // prints de or en
export const mutations = {
setCurrentBlogpost(state, currentBlogpost) {
const normalizedBlogpost = {
headline: headline,
};
state.currentBlogpost = normalizedBlogpost;
}
};
But now, it just sets the property as a String. Is there a way to manipulate the input properties, for my issue?
Edit: I got it running like this. But I feel like, there is a way simpler way to achieve this.
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;
}
}
currentBlogpost.Headline_deis equivalent tocurrentBlogpost["Headline_de"].