[Vuejs]-(VueJS) Update component whenever displayed

2👍

updated fires whenever data passed to your component changes. Therefore it will work if you pass in whatever condition controls your v-show, as a prop.

Generic example:

Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('child', {
  props: {
    shown: {
      type: Boolean,
      default: true
    }
  },
  template: '<div>{{shown}}</div>',
  mounted() {
    console.log('child mounted');
  },
  updated() {
    // runs whenever any prop changes
    // (optional condition) only run when component is shown
    if (this.shown) {
      console.log('child updated');
    }
  }
});
new Vue({
  el: '#app',
  data: () => ({
    showChild: true
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <label><input type="checkbox" v-model="showChild" /> Show child</label>
  <child v-show="showChild" :shown="showChild" />
</div>

Now updated hook works properly, because it fires everytime :shown changes its value, which maps precisely on your show/hide logic.

👤tao

0👍

maybe you can achieve it in two ways

1.use :key
whenever you want to rerender your component whether it is shown, change the value of key can rerender it.

<template>
    <h1 :key="key">Text</h1>
</template>
<script>
export default{
    data(){
        return {
            key:this.getRandomString()
        }
    },
    methods(){
        getRandomString(length = 32) {
          let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
          let max_pos = chars.length;
          let random_string = '';
          for (let i = 0; i < length; i++) {
            random_string += chars.charAt(Math.floor(Math.random() * max_pos));
          }
          return random_string;
        },
        yourMethod(){
            // communicate with backend
            let data = await axios.get(...);

            this.key = this.getRandomString();
        }
    }
}
</script>
  1. use vm.$forceUpdate()
...
    yourMethod(){
        // communicate with backend
        let data = await axios.get(...);

        this.$forceUpdate();
    }
...

-1👍

you could implement this in a couple of ways. However since you would like to got the v-show way, here is how I would suggest you go about it.

v-show (v-show, watcher):

The v-show is definitely dependent on a variable (data, or computed). Create a watcher, to watch that data/computed property change. Depending on the value of the data/computed property, execute whatever function you intend to on the watcher.

Leave a comment