vue路由
对于普通的网站,所有的超链接都是URL地址,所有的URL地址都对应服务器上对应的资源;
对于单页面应用程序来说,主要通过URL中的hash(#号)来实现不同页面之间的切换,同时,hash有一个特点:HTTP请求中不会包含hash相关的内容;所以,单页面程序中的页面跳转主要用hash实现;
在单页面应用程序中,这种通过hash改变来切换页面的方式,称作前端路由(区别于后端路由);
前端的路由:就是根据不同的Hash地址,在页面上展示不同的前端组件;
路由的嵌套
在一个页面上显示一个子页面,不能覆盖当前的页面
在路由规则中添加children 属性
- 显示
<!-- 路由链接 -->
<router-link to="/account">显示账号组件</router-link>
<router-link to="/newlist">新闻列表组件</router-link>
<!-- 路由的容器 -->
<router-view></router-view>
</div>
- 定义路由组件
const account= {
template: `<div class="account">
<h1>登录组件</h1>
<router-link to="/account/login">登录</router-link>
<router-link to="/account/reg">注册</router-link>
<router-view></router-view>
</div>`
}
const newlist={
template:`
<div class="newlist">
<h1>新闻组件</h1>
</div>
`
}
const login={
template:`
<div>
<h3>登录</h3>
</div>
`
}
const reg={
template:`
<div>
<h3>注册</h3>
</div>
`
}
- 创建路由对象(匹配路由规则)
路由嵌套:使用children属性
注意:子路由的path不要加斜线 /
const router = new VueRouter({
routes: [//路由规则
{path:'/account',component:account,children:[
//account 规则的子路由规则
{path:'login',component:login},
{path:'reg',component:reg}
]},
{path:'/newlist',component:newlist},
]
})
- 挂载路由对象
var vm = new Vue({
el: '#app',
data: {},
methods: {},
router
});