loading...
Key to Vue js

Published: June 2020

How to update your Vue js app easily - best practice

Usually Vue js updates everything automatically but sometimes its reactivity system is not working for you and you start thinking about: how do I re-render a component.

Markus A. Wolf

Author: Markus A. Wolf
Taipei / Taiwan – UX Designer and product owner - worked in Germany, California / Silicon Valley and now Taiwan for international clients.

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 Vue js 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 Vue js. 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.

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 Vue js and Tailwind CSS at Github: App.vue.