Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reload a vue component?

I know the solution is update the prop data like this :

this.selectedContinent = ""

But I want to use another solution

After I read some reference, the solution is :

this.$forceUpdate()

I try it, but it does not work

Demo and full code like this :

https://jsfiddle.net/Lgxrcc5p/13/

You can click button test to try it

I need a solution other than update the property data

like image 771
moses toh Avatar asked Sep 14 '17 05:09

moses toh


3 Answers

You have to assign a key to your component. When you want to re-render a component, you just update the key. More info here.

<template>
    <component-to-re-render :key="componentKey" />
</template>

export default {
  data() {
    return {
      componentKey: 0
    }
  },
  methods: {
    forceRerender() {
      this.componentKey += 1
    }
  }
}
like image 192
Ilyich Avatar answered Nov 13 '22 09:11

Ilyich


I use v-if to render the component:

<div id="app">
      <button type="button" @click="updateComponent">test</button>
      <test-el v-if="show"></test-el>
</div>

demo

like image 5
Julien Avatar answered Nov 13 '22 10:11

Julien


You can use Object.assign to assign initial data properties.

Instead of this.$forceUpdate()

You should use Object.assign(this.$data,this.$options.data.call(this)).

Here we using this.$options.data get original data and assigning this values to this.$data.

See the updated fiddle Link.

Update:

Another method: Link

like image 3
Shubham Patel Avatar answered Nov 13 '22 10:11

Shubham Patel