vue3 重新加载组件
时间: 2023-08-28 12:06:06 浏览: 52
在 Vue 3 中,可以使用 `key` 属性来强制重新加载组件。当 `key` 值发生变化时,Vue 会销毁当前的组件实例并重新创建一个新的组件实例。
例如,假设我们有一个组件 `MyComponent`:
```vue
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: {
id: {
type: String,
required: true
}
},
data() {
return {
message: ''
}
},
mounted() {
this.fetchData()
},
methods: {
fetchData() {
// 根据 this.id 获取数据
this.message = '数据加载完成'
}
}
}
</script>
```
如果我们想要在 `id` 发生变化时重新加载组件,可以将 `id` 绑定到 `key` 属性上:
```vue
<template>
<MyComponent :key="id" :id="id" />
</template>
<script>
import MyComponent from './MyComponent.vue'
export default {
components: {
MyComponent
},
data() {
return {
id: '1'
}
},
methods: {
reload() {
// 改变 id,强制重新加载组件
this.id = '2'
}
}
}
</script>
```
当我们调用 `reload` 方法时,Vue 会销毁当前的 `MyComponent` 实例并重新创建一个新的 `MyComponent` 实例,从而触发数据重新加载。