您的位置:首页 > 产品设计 > UI/UE

vue-router2.0,子路由的使用

2016-11-11 10:47 671 查看

Redirect and Alias

Redirect

Redirecting is also done in the 
routes
 configuration. To redirect from 
/a
 to 
/b
:

const router = new VueRouter({
routes: [
{ path: '/a', redirect: '/b' }
]
})

The redirect can also be targeting a named route:

const router = new VueRouter({
routes: [
{ path: '/a', redirect: { name: 'foo' }}
]
})

Or even use a function for dynamic redirecting:

const router = new VueRouter({
routes: [
{ path: '/a', redirect: to => {
// the function receives the target route as the argument
// return redirect path/location here.
}}
]
})

For other advanced usage, checkout the example.

Alias

A redirect means when the user visits 
/a
, and URL will be replaced by 
/b
, and then matched as 
/b
. But what is an alias?

An alias of 
/a
 as 
/b
 means when the user visits 
/b
, the URL remains 
/b
, but it will be matched as if the user is visiting 
/a
.

The above can be expressed in the route configuration as:

const router = new VueRouter({
routes: [
{ path: '/a', component: A, alias: '/b' }
]
})

An alias gives you the freedom to map a UI structure to an arbitrary URL, instead of being constrained by the configuration's nesting structure.

源码示例

app.js

import
Vue from
'vue'
 import
VueRouter from
'vue-router'
  
 Vue.use(VueRouter)
  
 const
Home = { template:
'<div><h1>Home</h1><router-view></router-view></div>' }
 const
Foo = { template:
'<div>foo</div>' }
 const
Bar = { template:
'<div>bar</div>' }
 const
Baz = { template:
'<div>baz</div>' }
 const
Default = { template:
'<div>default</div>' }
  
 const
router =
new VueRouter({
 mode:
'history',
 base:
__dirname,
 routes: [
 { path:
'/home', component: Home,
 children: [
 // absolute alias
 { path:
'foo', component: Foo, alias:
'/foo' },
 // relative alias (alias to /home/bar-alias)
 { path:
'bar', component: Bar, alias:
'bar-alias' },
 // multiple aliases
 { path:
'baz', component: Baz, alias: ['/baz',
'baz-alias'] },
 // default child route with empty string as alias.
 { path:
'default', component: Default, alias:
'' }
 ]
 }
 ]
 })
  
 new
Vue({
 router,
 template:
`
 <div id="app">
 <h1>Route Alias</h1>
 <ul>
 <li><router-link to="/foo">
 /foo (renders /home/foo)
 </router-link></li>
 
 <li><router-link to="/home/bar-alias">
 /home/bar-alias (renders /home/bar)
 </router-link></li>
 
 <li><router-link to="/baz">
 /baz (renders /home/baz)</router-link>
 </li>
 
 <li><router-link to="/home/baz-alias">
 /home/baz-alias (renders /home/baz)
 </router-link></li>
 
 <li><router-link to="/home">
 /home (renders /home/default)
 </router-link></li>
 </ul>
 <router-view class="view"></router-view>
 </div>
 `
 }).$mount('#app')
参考https://router.vuejs.org/en/api/router-view.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: