Named routes name
are configured using properties,
const router=new VueRouter({
routes:[
{
path:'/user/:userid',
name:'user',//设置name属性
component:User
}
]
})
So the route is set up, how to link to the route ? The difference between
a named route and other routes is that instead of using the to attribute when linking to a named route, v-bind:to is used , and the attribute value is not a path string, but an object .
<router-link :to="{ name:'user',params:{ userid:123 }}"
//等同于
router.push({ name:'user',params:{ userid:123}})
Here is a concrete example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HelloWorld</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const Home = { template: '<div>This is Home</div>' }
const Foo = { template: '<div>This is Foo</div>' }
const Bar = { template: '<div>This is Bar {{ $route.params.id }}</div>' }
const router = new VueRouter({
mode: 'history',
base:'__dirname',
routes: [
{ path: '/', name: 'home', component: Home },
{ path: '/foo', name: 'foo', component: Foo },
{ path: '/bar/:id', name: 'bar', component: Bar }
]
})
new Vue({
router,
template: `
<div id="app">
<h1>Named Routes</h1>
<p>Current route name: {{ $route.name }}</p>
<ul>
<li><router-link :to="{ name: 'home' }">home</router-link></li>
<li><router-link :to="{ name: 'foo' }">foo</router-link></li>
<li><router-link :to="{ name: 'bar', params: { id: 123 }}">bar</router-link></li>
</ul>
<router-view class="view"></router-view>
</div>
`
}).$mount('#app')
</script>
</body>
</html>