定义父路由组件和子路由组件(注意,父组件中的子组件的to属性要包括父路由地址“main”)
<template id="main">
<div>
<h3>主页面</h3>
<router-link to="/main/login" tag="button">登录</router-link>
<router-link to="/main/register" tag="button">注册</router-link>
<transition appear>
<router-view></router-view><!--新增加的路由组件占位符(不会覆盖之前地占位符里的组件)-->
</transition>
</div>
</template>
var mainPage={
template:"#main" ,
}
var login={
template:'<h4 class="login">登录界面----</h4>',
}
var register={
template:'<h4 class="register">注册界面----</h4>'
}
在vue-router对象中为父路由组件配置子路由组件属性children(注意,子路由组件不用在外部再次定义,子路由组件的path属性不带“/”)
var router=new VueRouter({
routes:[//路由匹配规则
{
path:'/main',
component:mainPage,
children:[//children属性下的子组件的path不要带 / ,否则永远以根目录开始请求,不方便用户理解和书写url地址
{path:'login',component:login},//子组件,path路径不用带/
{path:'register',component:register},
]
},
// {path:'/login/:address',component:login},//占位符传参
// {path:'/register',component:register},
]
});
完整实例代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="../../js/Vue.js" ></script>
<script src="../../js/vue-router.js" type="text/javascript" charset="utf-8"></script>
<style>
/*组件的样式*/
.login,.register{
width: 400px;
height: 400px;
text-align: center;
background: yellowgreen;
position: absolute;/*平稳切换*/
}
.register{
background: cornflowerblue;
}
/*默认切换路由时候的激活样式*/
.router-link-active{
color: red;
font-size: 24px;
font-weight: 800;
}
/*切换组件时候的动画效果*/
.v-enter,.v-leave-to{
opacity: 0;
transform: translate(100px,100px);
}
.v-enter-active,.v-leave-active{
transition: all .5s;
}
</style>
</head>
<body>
<template id="main">
<div>
<h3>主页面</h3>
<router-link to="/main/login" tag="button">登录</router-link>
<router-link to="/main/register" tag="button">注册</router-link>
<transition appear>
<router-view></router-view><!--新增加的路由组件占位符(不会覆盖之前地占位符里的组件)-->
</transition>
</div>
</template>
<div id="app">
<router-link to="/main">打开主页面</router-link>
<transition appear>
<router-view></router-view><!--路由组件占位符-->
</transition>
</div>
<script>
var mainPage={
template:"#main" ,
}
var login={
template:'<h4 class="login">登录界面----</h4>',
}
var register={
template:'<h4 class="register">注册界面----</h4>'
}
var router=new VueRouter({
routes:[//路由匹配规则
{
path:'/main',
component:mainPage,
children:[//children属性下的子组件的path不要带 / ,否则永远以根目录开始请求,不方便用户理解和书写url地址
{path:'login',component:login},//子组件,path路径不用带/
{path:'register',component:register},
]
},
// {path:'/login/:address',component:login},//占位符传参
// {path:'/register',component:register},
]
});
var vm=new Vue({
el:"#app",
data:{
},
methods:{
},
components:{
},
router:router,//注册路由
});
</script>
</body>
</html>