VueRouter声明:
const router = new VueRounter({
routes: [
{name: 'Home', path: '/', component: Home},
{name: 'Category', path: '/category', component: Category},
{name: 'Product', path: '/product/:id', component: Product},
{name: 'Me', path: '/me', component: Me},
]
})
在引用路由的时候,一般在 <router-link> 或者 js 中,我们可能会直接写成这样:
<template>
<router-link to="/product/12">
...
</router-link>
</template>
<script>
export default {
methods: {
jump() {
this.$router.push("/product/12")
}
}
}
</script>
问题
这样显示地引用路径,延续了我们在普通 html 中使用 <a href> 的习惯,但是会带来隐藏的麻烦:
当 path 产生变更,除了需要修改 router 定义,还要修改所有引用,这些引用不仅可能在 <router-link> 中,还可能在 js 中使用 this.$router,将带来很多工作量和麻烦。
建议
建议向 to 属性传入一个对象显示声明路由的名称:
<template>
<router-link to="{ name: 'Product', params: { id: 12 } }">
...
</router-link>
</template>
<script>
export default {
methods: {
jump() {
this.$router.push({
name: 'Product',
params: { id: 12 }
})
}
}
}
</script>
疑问
可能会有一个疑问:
name 属性值变更,不也是要进行同样工作量的修改?
但是路径是直接显示在地址栏的,是可以被测试者、使用者乃至你的上级看到,可想而知有更大的概率会产生变更的需求;
而 name 是写在代码里面的,除非技术总监或组长看不顺眼,否则变更的概率会比以上低很多。