How can I reload a vue component?

Viewed 81005

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

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

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();.

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

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

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.

Related