Here is the best way to do this
I started asking myself this question after struggling with multi language support and changing the language in may Vue js application.
So how can I get Vue jsto re-render a component? If you search for VueJS and how to force an update then you might find articles telling you “Vue.forceUpdate()” is the best way. Hold on for a sec - what is it you really want?
In my case I handled some meta descriptions in the Vuex store. Every new page triggers the meta text so it ends up in the dom. The trigger was the new route but I wasn’t including the language in the url as a prop. I tried several approaches and I ended up using one single computed property to solve everything. By the way, using this technique is a great way to learn more about how changes get tracked in
VueJS
. I used a computed property together with the route path and the actual language - something like /home/en
or /icon/es
.
Then I used this as the key for the router view inside the major app component. Everytime the language changes the computed property gets changed and if the key changes the whole view gets re-rendered - wow fast, easy and reliable.
- Works with Vue router
- Great multi language support with i18n
- Here you can find out more about “ The Key Changing Technique ”
The Key Changing Technique
<template>
<div id="app">
<transition name="page" mode="out-in">
<router-view :key="route_name_key" />
</transition>
</div>
</template>
<script>
export default {
name: 'Home',
computed: {
route_name_key: function() {
return this.$route.path + '/' + this.language
},
},
}
</script>
You can find the code example in my collection of best practices in VueJS and Tailwind CSS at Github: App.vue .