Vue/Nuxt2环境下路由跳转后$bvToast提示框不显示如何解决?
问题根源
你遇到的问题本质是两个原因共同导致的:
- vue-router 3.x 版本中,
$router.push的onComplete回调执行时机是路由导航被全局确认、但新页面组件还未完成挂载、旧页面组件即将销毁的阶段,你的console.log能正常执行说明回调确实触发了。 - BootstrapVue 的
$bvToast默认会将提示框挂载到当前调用该方法的组件的 DOM 节点下,你在登录页组件中调用this.$bvToast,回调执行后登录页组件立刻被销毁,对应的 DOM 节点被移除,已经触发但还没渲染完成的 toast 自然就看不到了。
解决方案
这里提供三种可落地的方案,按需选择即可:
方案1:直接调用根实例的 toast 实例(最快修复)
直接调用挂载在 Vue 根实例上的 $bvToast,不受子组件销毁的影响:
this.$router.push('/dashboard', () => { console.log('hiiiii') this.$root.$bvToast.toast('Welcome!', { title: 'Message', solid: true, variant: 'success' }) })
方案2:将提示逻辑放到新页面的生命周期中
跳转时带一个临时参数,在 dashboard 页面挂载后判断参数触发提示,不会残留无用参数:
// 登录页跳转逻辑 this.$router.push('/dashboard?welcome=1')
// dashboard 页面组件 mounted() { if (this.$route.query.welcome === '1') { this.$bvToast.toast('Welcome!', { title: 'Message', solid: true, variant: 'success' }) // 清除路由参数,避免刷新页面重复触发提示 this.$router.replace({ query: { ...this.$route.query, welcome: undefined } }) } }
方案3:全局状态+路由守卫(最优雅,适合多场景复用)
用 Vuex 存全局标记,配合路由后置守卫统一处理提示,适合后续有更多全局提示的场景:
- 先在 Vuex 中新增状态和修改方法:
// store/index.js export const state = () => ({ showWelcomeToast: false }) export const mutations = { SET_SHOW_WELCOME_TOAST(state, value) { state.showWelcomeToast = value } }
- 登录成功后先修改状态再跳转:
// 登录页逻辑 this.$store.commit('SET_SHOW_WELCOME_TOAST', true) this.$router.push('/dashboard')
- 新增路由插件监听跳转完成事件:
// plugins/route-toast.js export default ({ app, store }) => { app.router.afterEach(() => { if (store.state.showWelcomeToast) { app.$bvToast.toast('Welcome!', { title: 'Message', solid: true, variant: 'success' }) store.commit('SET_SHOW_WELCOME_TOAST', false) } }) }
- 在
nuxt.config.js中注册插件:
// nuxt.config.js export default { plugins: [ '~/plugins/route-toast.js' ] }
内容的提问来源于stack exchange,提问作者Rey
相关产品推荐
相关产品推荐

