vue 路由的 meta 如何根据接口动态设置?

比如我要进入一个详情页面,进入前的参数只有 id 值

我要通过这个id去查询详情接口,并把返回的详情中的名称设置为路由的 meta 中的title

此时我要如何实现?

阅读 1.2k
avatarAI BotBETA

首先,你需要明白Vue Router的meta属性是静态的,不能动态地根据接口返回的数据来设置。但是,你可以在路由守卫(如全局前置守卫)中获取接口数据,并设置到路由的meta属性中。

以下是一个可能的实现方式:

  1. 在你的路由配置中,为需要设置meta的路由添加一个key值,比如:
const routes = [
  {
    path: '/detail/:id',
    name: 'detail',
    component: Detail,
    meta: { title: '默认标题' }, // 这里设置默认的meta值
    props: true // 通过props将id传递给Detail组件
  }
  // 其他路由...
]
  1. 在全局前置守卫中获取接口数据并设置到路由的meta属性中:
router.beforeEach((to, from, next) => {
  // 获取id值
  const id = to.params.id;
  // 使用id去查询详情接口,假设返回一个Promise对象
  fetchDetail(id).then(response => {
    // 将返回的详情中的名称设置为路由的meta中的title
    to.meta.title = response.name;
    next();
  }).catch(error => {
    console.error(error);
    next(false); // 如果出错,跳转到错误页面
  });
});

这样,每次访问/detail/:id时,都会先通过全局前置守卫去查询详情接口,并将返回的名称设置到路由的meta的title中。如果查询失败,则会跳转到错误页面。

1 个回答

补充新回答

组件内

routeTo:null //data定义

watch: {
      $route: {
        handler(to, form) {
          this.routeTo = to;
          console.log(to);
          console.log(form);
        },
        immediate: true
      }
    }

获取到name 调用routeTo修改

 setTimeout(()=>{
        this.routeTo.meta.title='测试测试';
        console.log(this.$route)
      },1000)

旧回答

跳转详情时把要改的名字带上去

  this.$router.push({
          path: 'xxxxx',
          query: {name}//name就是你要显示的名字
        });

然后在路由文件里改

 {
      path: 'xxxxx',
      name: 'xx',
      component: 'xxxxx',
      meta: {
        title: '',
      },
      beforeEnter: (to, from, next) => {
        to.meta.title = to.query.name ? `${to.query.name}` : '通用名字';
        next()
      },
    },
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题