如何实现从指定组件路由跳转后自动触发目标组件函数?
解决方案
步骤1:在ComponentTwo的跳转链接中添加标识参数
修改ComponentTwo中路由跳转的to属性,添加查询参数标记跳转来源:
computed: { fields() { return [ { label: this.$t('name'), sortable: true, template: { type: 'link', action: () => this.showModal = false, label: data => data.item.userID, // 跳转路径改为ComponentOne的路由,并添加来源标记参数 to: data => `/component-one/${data.item.id}?fromComponentTwo=true` } }, ] } }
注:请根据实际项目中ComponentOne的路由路径调整
/component-one/${data.item.id}部分。
步骤2:在ComponentOne中触发目标函数
在ComponentOne的mounted钩子(若组件启用keep-alive则用activated钩子)中,判断路由参数并执行函数,同时清除参数避免重复触发:
mounted() { if (this.$route.query.fromComponentTwo === 'true') { // 自动触发目标加载函数 this.$refs.myFunction.load() // 清除查询参数,防止页面刷新时重复执行 this.$router.replace({ query: { ...this.$route.query, fromComponentTwo: undefined } }) } }
备选方案:通过路由来源路径判断
如果不想用查询参数,可直接通过路由来源路径判断:
mounted() { // 假设ComponentTwo的路由路径以/component-two开头 if (this.$route.from.path.startsWith('/component-two')) { this.$refs.myFunction.load() } }
此方案无需修改ComponentTwo的跳转链接,但需保证ComponentTwo的路由路径固定易识别。
内容的提问来源于stack exchange,提问作者Maflec
相关产品推荐
相关产品推荐

