vue项目使用beforeEach钩子给url添加公共参数

使用场景:推广页面多渠道入口,数据统计需要;

代码:

router.beforeEach((to, from, next) => {
  if (!to.query.channel) {
    next({
      ...to,
      query: {
        ...to.query,
        'channel': '1'
      }
    })
  } else {
    next()
  }
})

知道的点:

        1、next接收的参数:在vueRouter文档中初步看了一下,没有具体说明。但我们常用的next({path: '/xxx'}) 不难推测,next接收的是to对象。

        2、to.query是只读属性,所以无法使用 to.query.xxx = 'xx'。

不知道的点:

        下面这种写法会进入死循环,为啥?后面再看看

next({path: to.path, query:{...to.query, 'xx': 'xx'}})

希望有点用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
很高兴回答你的问题。对于该问题,您可以按照以下步骤操作: 1. 在 main.js 中导入 VueVue-Router,并将 Vue.use(VueRouter)。 2. 在 router/index.js 文件中,定义多个 beforeEach 钩子函数。 3. 在其中一个 beforeEach 钩子函数中,使用 next(false) 中止路由导航。 4. 在另一个 beforeEach 钩子函数中,使用 next() 继续路由导航。 具体的代码实现可以参考以下示例: ``` // main.js import Vue from 'vue'; import VueRouter from 'vue-router'; import App from './App.vue'; import router from './router'; Vue.config.productionTip = false; Vue.use(VueRouter); new Vue({ router, render: (h) => h(App), }).$mount('#app'); ``` ``` // router/index.js import Vue from 'vue'; import VueRouter from 'vue-router'; import Home from '../views/Home.vue'; import About from '../views/About.vue'; Vue.use(VueRouter); const routes = [ { path: '/', name: 'home', component: Home, }, { path: '/about', name: 'about', component: About, }, ]; const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes, }); router.beforeEach((to, from, next) => { console.log('beforeEach1'); next(false); }); router.beforeEach((to, from, next) => { console.log('beforeEach2'); next(); }); export default router; ``` 在上面的示例中,我们定义了两个 beforeEach 钩子函数。在第一个 beforeEach 钩子函数中,我们使用 next(false) 中止了路由导航。在第二个 beforeEach 钩子函数中,我们使用 next() 继续了路由导航。在控制台中可以看到输出的 beforeEach1 和 beforeEach2 信息。 希望能够帮助到您。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值