moses toh
moses toh

Reputation: 13172

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

Upvotes: 15

Views: 103197

Answers (7)

Salma EL HAJRAOUI
Salma EL HAJRAOUI

Reputation: 196

On vuejs3 :

<template>
  <render-component :key="count" />
  <span @click="renderComponent">Click to reload render-component</span>
</template>

<script>
import { ref } from 'vue'
export default {
   setup() {
    const count = ref(0)

    const renderComponent = () => {
     count.value++
    }
    return {
     count,
     renderComponent
    }
   }
}
</script>

see gist

Upvotes: 0

Balaji
Balaji

Reputation: 10887

Simplest one

For your data in object use your key as JSON.stringify(data)

  <component :key="JSON.stringify(data)" :data="data" />

just update your state

$vm.data={
name:'balaji'
}

it automaticly update your component

Upvotes: 2

ThriftyNick
ThriftyNick

Reputation: 47

I thought I needed to reload, but I was able to move everything inside the mounted hook to an init method. The mounted hook calls the init method, and if you need the parent to reload everything it can use a ref to call this.$refs.componentName.init();.

Upvotes: 2

Ilyich
Ilyich

Reputation: 5776

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
    }
  }
}

Upvotes: 57

Pulkit Aggarwal
Pulkit Aggarwal

Reputation: 2672

I also face the same issue. I used location.reload() for reloading the component.
This may be not the right way to solve this problem. But this solved my problem.

Upvotes: -7

Julien
Julien

Reputation: 1238

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

Upvotes: 5

Shubham Patel
Shubham Patel

Reputation: 3289

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

Upvotes: 4

Related Questions