<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
实例一、在路由中设置一个参数
html部分
<div id="app">
<p>
<router-link to="/user/foo">/user/foo</router-link>
<router-link to="/user/bar">/user/bar</router-link>
</p>
<router-view></router-view>
</div>
js部分
<script>
const User = {
template: '<div>User {{ $route.params.id }}</div>',
watch: {'$route' (to, from) {
//监听路由
console.log(to);
console.log(from);
}
}
}
实例二 在路由中设置多个路径参数
const router= new VueRouter({
routes:[{path:'/user/:id',component:User}]
})
new Vue({
router
}).$mount("#app")
</script>
<div id="app">
<p>
<router-link to="/user/evan/post/123">/user/foo</router-link>
<router-link to="/user/evan/post/456">/user/bar</router-link>
</p>
<router-view></router-view>
</div>
<script>
const User = {
template: '<div>User {{ $route.params.post_id }} {{ $route.params.username }}</div>',
watch: {'$route' (to, from) {
console.log(to);
console.log(from);
}
}
}
const router= new VueRouter({
routes:[{path:'/user/:username/post/:post_id',component:User}]
})
new Vue({
router
}).$mount("#app")
</script>
高级匹配中可以进行正则的匹配
routes: [
{ path: '/' },
// params are denoted with a colon ":"
{ path: '/params/:foo/:bar' },
// a param can be made optional by adding "?"
{ path: '/optional-params/:foo?' },
// a param can be followed by a regex pattern in parens
// this route will only be matched if :id is all numbers
{ path: '/params-with-regex/:id(\d+)' },
// asterisk can match anything
{ path: '/asterisk/*' },
// make part of th path optional by wrapping with parens and add "?"
{ path: '/optional-group/(foo/)?bar' }
]
除了 $route.params 外,$route 对象还提供了其它有用的信息,例如,$route.query(如果 URL 中有查询参数)、$route.hash 等等。你可以查看 API 文档 的详细说明。