什么是路由
路由是一个比较抽象的概念,一言蔽之,路由就是 ‘ 分发请求 ’,路由可以通过不同的请求,将用户接入到不同的url,不同的端口。
我们现在一般使用三种路由:hash,history,memory
hash
hash通过window.location.hash 获取 路径 (#xxx),在通过 hashchange 监听 路径的变化,就可以实现页面的跳转。
缺点:
- 使用hash会造成SEO不友好,因为#后面的内容是不会上传到服务器的
history
history通过 window.location.pathname 获取到路径,(使用a标签时,需阻止其默认动作),在通过window.history.pushState(xxx,xxx,href)使用history,之后我们就可以自己调用一个函数,路由到href
缺点
- 需要后端配合将所有前端路由都渲染到同一个页面
- 不支持IE8以下的浏览器
memory
与hash和history不同,memory需要将路径存储中localStorage中来进行路由,这样做的好处是每次重新打开界面,我们会进入上次使用的页面。
缺点
- 由于memory不通过url存储路径,所以当你将页面分享给他人时,他人只能进入主页。
VueRouter 的简单使用
我们首先可以通过官网安装VueRouter。
- 在vue文件中,写上链接标签及视图标签
<template>
<div>
<router-link to="/child"> to child</router-link>
<router-link to="/child2"> to child2</router-link>
<router-view></router-view>
</div>
</template>
- 创建一个js文件,配置路由表,并进行封装
import Vue from 'vue'
import VueRouter from 'vue-router'
import child from "../components/child"
import child2 from "../components/child2"
Vue.use(VueRouter)
const routes = [
{path:'/child' , component: child},
{path: '/child2',component: child2},
{path: '/',components: child}
]
const router = new VueRouter({
routes
})
export default router
- 挂载router
new Vue({
render : h => h(App),
router,
el: '#app'
})