检查你在 Vue 中哪个页面的最佳方式.js



我有

当我在汽车详细信息页面中时,这些简单的路线/URL

http://localhost:8080/car/1

我正在使用vue2;检查我是否在car页面上的最佳方法是什么?

我通常

我会检查URL的第一段,但我不确定这是否是最好的经得起未来考验的方法。

问题

我应该使用JS来检测我是什么页面吗?

我应该使用Vue功能来访问路由器对象吗?

为什么一个人会决定选择一个而不是另一个?

您可以在routes定义中为您的路线提供一个名称,如:

{
path: '/car/{id}',
name: 'car',
component: CarView
},

然后使用this.$route.name访问它,或者可以使用字符串对象方法解析this.$route.path以获得名称

也许,尝试使用:router.currentRoute.path,其中路由器是:

import Router from "vue-router";
Vue.use(Router);
const routes = [
{ path: "/", component: Home },
{ path: "/test1", component: Test1 },
{ path: "/test2", component: Test2 }
];
const router = new Router({
routes
});
console.log('Current route: ', router.currentRoute.path);

最新更新