Vue Router 中如何获取路由传递过来的参数?

在 Vue Router 中,可以通过多种方式获取路由传递过来的参数。以下是几种常见的方法:

使用 this.$route.params

在组件中,可以通过 this.$route.params 来访问路由参数。例如,假设你有一个路由配置如下:

const routes = [
  {
    path: '/user/:id',
    component: UserComponent
  }
];

在 UserComponent 组件中,你可以这样获取 id 参数:

export default {
  name: 'UserComponent',
  mounted() {
    const userId = this.$route.params.id;
    console.log('User ID:', userId);
  }
};

使用 props 传递参数

你也可以通过 props 将路由参数传递给组件。首先,在路由配置中启用 props 选项:

const routes = [
  {
    path: '/user/:id',
    component: UserComponent,
    props: true
  }
];

然后在组件中定义 props

export default {
  name: 'UserComponent',
  props: ['id'],
  mounted() {
    console.log('User ID:', this.id);
  }
};

使用 beforeRouteEnter 导航守卫

如果你需要在组件渲染之前获取路由参数,可以使用 beforeRouteEnter 导航守卫:

export default {
  name: 'UserComponent',
  beforeRouteEnter(to, from, next) {
    next(vm => {
      const userId = to.params.id;
      console.log('User ID:', userId);
    });
  }
};

使用 watch 监听路由变化

如果你的组件需要在路由参数变化时执行某些操作,可以使用 watch 监听 $route 对象的变化:

你可能感兴趣的:(面试题整理专题,vue.js,javascript,前端)