How can I reload a vue component?

对着背影说爱祢 提交于 2019-12-10 18:35:59

问题


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


回答1:


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



回答2:


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




回答3:


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




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/46211297/how-can-i-reload-a-vue-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!