一、核心思路与实现方案
当从父组件跳转到其他页面,返回后想重新加载子组件,核心是让父组件感知「页面返回」事件,然后主动触发子组件的刷新逻辑(如重新请求数据、重置子组件状态)。以下是 2 种常用且易理解的方案,按「简单→灵活」排序。
方案 1:利用页面生命周期 onShow(最简单)
onShow 是 UniApp 页面的生命周期,每次页面显示(包括跳转返回)都会执行。通过在父组件的 onShow 中触发子组件的刷新方法,实现子组件重新加载。
步骤 1:父组件(页面)代码
<template>
<!-- 引入子组件,并绑定 ref(关键:通过 ref 调用子组件方法) -->
<child-component ref="childRef"></child-component>
<!-- 跳转按钮 -->
<button @click="gotoOtherPage">跳转到其他页面</button>
</template>
<script>
// 引入子组件
import childComponent from '@/components/childComponent.vue';
export default {
components: {
childComponent
},
// 页面显示时(包括返回)执行
onShow() {
// 调用子组件的刷新方法
if (this.$refs.childRef) {
this.$refs.childRef.reloadData(); // 触发子组件重新加载
}
},
methods: {
// 跳转到其他页面
gotoOtherPage() {
uni.navigateTo({
url: '/pages/other/other-page' // 目标页面路径
});
}
}
};
</script>
步骤 2:子组件代码
<template>
<view>子组件内容:{{ list }}</view>
</template>
<script>
export default {
data() {
return {
list: [] // 子组件需要加载的数据
};
},
onLoad() {
// 初始化加载数据
this.reloadData();
},
methods: {
// 定义刷新方法(供父组件调用)
reloadData() {
// 模拟重新请求接口/加载数据(核心:子组件的重新加载逻辑)
uni.request({
url: '/api/get-data',
success: (res) => {
this.list = res.data.data; // 更新子组件数据
}
});
}
}
};
</script>
核心说明:
ref="childRef":给子组件绑定唯一标识,父组件通过this.$refs.childRef能直接访问子组件的方法 / 数据;onShow:返回父页面时会自动执行,触发子组件的reloadData方法,实现子组件重新加载;- 优点:代码最简单,无需全局事件,适合大多数场景;
- 注意:
onShow在页面首次加载、跳转返回时都会执行,若想「仅返回时刷新」,可加标记区分(见方案 2)。
方案 2:全局事件 uni.$emit/$on(精准控制)
如果需要「仅在其他页面主动触发刷新时」重新加载子组件(而非每次 onShow 都刷新),可通过全局事件实现:跳转页面返回前触发事件,父组件监听事件后刷新子组件。
步骤 1:父组件代码
<template>
<child-component ref="childRef"></child-component>
<button @click="gotoOtherPage">跳转到其他页面</button>
</template>
<script>
import childComponent from '@/components/childComponent.vue';
export default {
components: {
childComponent
},
onShow() {
// 监听全局事件 "refreshChild"(页面加载时只绑定一次)
this.refreshListener = uni.$on('refreshChild', () => {
this.$refs.childRef.reloadData(); // 刷新子组件
});
},
onUnload() {
// 页面销毁时移除监听(避免内存泄漏)
uni.$off('refreshChild', this.refreshListener);
},
methods: {
gotoOtherPage() {
uni.navigateTo({
url: '/pages/other/other-page'
});
}
}
};
</script>
步骤 2:其他页面(跳转目标页)代码
<template>
<button @click="goBack">返回并刷新子组件</button>
</template>
<script>
export default {
methods: {
goBack() {
// 1. 触发全局事件,通知父组件刷新子组件
uni.$emit('refreshChild');
// 2. 返回上一页(父组件)
uni.navigateBack();
}
}
};
</script>