模板抽离
我们已经学习过了Vue模板的另外定义形式,使用<template></template>
。
<template id="home">
<div>首页</div>
</template>
<template id="news">
<div>新闻</div>
</template>
然后js里定义路由组件的时候:
const Home = { template: '#home' };
const News = { template: '#news' };
路由嵌套
实际应用界面,通常由多层嵌套的组件组合而成。
比如,我们 “首页”组件中,还嵌套着 “登录”和 “注册”组件,那么URL对应就是/home/login
和/home/reg
。
<template id="home">
<div>
<h2>首页</h2>
<router-link to="/home/login">登录</router-link>
<router-link to="/home/reg">注册</router-link>
<router-view></router-view>
</div>
</template>
这是访问/home
后的模板,其中我们需要把/home/login
和/home/reg
渲染进来。
完成上面代码后,HTML结构如下图:
- 登录和注册2个组件
<template id="login">
<div>登录界面</div>
</template>
<template id="reg">
<div>注册界面</div>
</template>
const Login = { template: '#login' };
const Reg = { template: '#reg' };
3.定义路由
const routes = [
{ path: '/', redirect: '/home' },
{
path: '/home',
component: Home,
children:[
{ path: '/home/login', component: Login},
{ path: '/home/reg', component: Reg}
]
},
{ path: '/news', component: News}
]
注意我们在home
路由配置了它的children。这就是嵌套路由。
4.案例全部代码如下:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="http://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="box">
<p>
<router-link to="/home">home</router-link>
<router-link to="/news">news</router-link>
</p>
<router-view></router-view>
</div>
<template id="home">
<div>
<h2>首页</h2>
<router-link to="/home/login">登录</router-link>
<router-link to="/home/reg">注册</router-link>
<router-view></router-view>
</div>
</template>
<template id="news">
<div>新闻</div>
</template>
<template id="login">
<div>登录界面</div>
</template>
<template id="reg">
<div>注册界面</div>
</template>
<script type="text/javascript">
const Home = { template: '#home' };
const News = { template: '#news' };
const Login = { template: '#login' };
const Reg = { template: '#reg' };
const routes = [
{ path: '/', redirect: '/home' },
{
path: '/home',
component: Home,
children:[
{ path: '/home/login', component: Login},
{ path: '/home/reg', component: Reg}
]
},
{ path: '/news', component: News}
]
const router = new VueRouter({
routes
})
const app = new Vue({
router
}).$mount('#box')
</script>
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)