English | 简体中文
Reload a vue component (support vue2.3+ and vue3), make it go through lifecycle again.
E.g. you have a detail component accept id prop and do some complex init and fetch data and render during lifecycle, after submit some changes to server, you may want detail component redo all things again. that's vue-reload good at.
pnpm i vue-reload
# or
npm i vue-reload
# or
yarn add vue-reload
if you use vue2.x, just change import from
vue-reload
tovue-reload/compat
, which support both vue2.3+ and vue3.
register global property in main.ts
import { createApp } from 'vue'
import { createReload } from 'vue-reload';
import App from './App.vue'
const app = createApp(App)
app.use(createReload())
app.mount('#app')
For vue 2.x:
Vue.use(createReload())
then, you can just call $reload()
in any component template, like:
<template>
<button @click="$reload()">$reload</button>
</template>
Don't use like
<button @click="$reload">$reload</button>
, since$reload
usethis
as component instance
<script setup lang="ts">
import { useReload } from 'vue-reload';
const reload = useReload()
</script>
<template>
<button @click="reload()">reload</button>
</template>
<script setup lang="ts">
import { useTemplateRef } from 'vue';
import { useReload } from 'vue-reload';
import Child from './Child.vue'
const refChild = useTemplateRef('refChild')
const reloadChild = useReload(refChild)
</script>
<template>
<Child ref="refChild" />
<button @click="reloadChild()">reloadChild</button>
</template>
If you register
$reload
globally AND use vue 2.x, you can just call$refs.refChild.$reload()
. Since vue3 introduced closed instance, can't access global property from ref, we should use composable.
- add support for vue2.7, code like:
this.$vnode.key = Symbol('reload') this.$parent.$forceUpdate()
- support reload child component
- since setup component has closed instance,
$reload
is not exposed, so we can't just use$refs.xxx.$reload
: vuejs/core#5022 (comment)
- since setup component has closed instance,
- add support for vue 2.x
- support 2.3+, since vue support esm from 2.3
- add test for vue2.7