标准使用
- npm install vue-router --save
- 在src目录下,新建router文件夹,分别新建routes.js,index.js文件
- routes.js代码如下所示:
import Home from './../views/Home';
import About from './../views/About';
export default [
{
path:'/home',
component:Home
},
{
path:'/about',
component:About
}
]
- index.js代码如下所示:
import VueRouter from 'vue-router';
import routes from './routes'
import Vue from 'vue';
Vue.use(VueRouter);
export default new VueRouter({
mode:'hash',
routes:routes
})
- 在main.js将vue-router引入
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')
- 在App.vue使用路由跳转,代码如下:
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<div>
<router-link to="/Home" style="margin-right: 10px;">Home</router-link>
<router-link to="/About">About</router-link>
</div>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'app',
mounted(){
window.console.log(this.$router, this.$route);
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
注意
- 这里需要注意 this.$route ,this.$router分别不同
this. r o u t e 集 合 了 参 数 , t h i s . route集合了参数,this. route集合了参数,this.router集合了方法
原理分析
hash模式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="#/home">Home</a>
<a href="#/about">About</a>
<div id="app"></div>
<script>
var html = document.getElementById("app");
window.addEventListener('load', ()=>{
html.innerText = location.hash.slice(1)
})
window.addEventListener('hashchange', ()=>{
html.innerText = location.hash.slice(1)
})
</script>
</body>
</html>
hash模式就是前面带个#号,在页面加载时,先调用load方法,在切换路由时,通过hashchange方法监听
路由变化
history模式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a onclick="go('/home')">Home</a>
<a onclick="go('/about')">About</a>
<div id="app"></div>
<script>
var html = document.getElementById("app");
function go(pathname) {
html.innerText = pathname;
history.pushState({}, null, pathname)
}
window.addEventListener('popstate', ()=>{
go(location.pathname);
})
</script>
</body>
</html>
- history模式与hash模式显示上区别就是有没有带 # 号
- 上述代码实现的就是history原理,有两个关键事件,pushstate与popstate,pushstate有三个参数,解释如下:
pushState(状态对象,标题,可选的URL地址)
状态对象,存储JSON字符串,可以用在popstate事件中。state可以是任何可以序列化的东西。火狐会把这些对象持久化,有大小限制
title,火狐已经忽略此参数,可以设置为null
URL,可以是相对地址,新的URL必须与当前URL同源。
pushState可以实现window.location的功能,但是pushState(hash不同的新url)不会触发hashchange事件- 通过history.pushstate即可实现路由跳转
- popstate主要针对的是,点击前进后退按钮,路由不刷新问题,通过监听popstate事件,即可实现前进后退时,路由,页面刷新
- 这种模式缺点就是容易造成404问题
源码实现
vue-router.js
class HistoryRoute{
constructor(){
this.current = null;
}
}
var mode = '';
class VueRouter{
constructor(options){
this.mode = options.mode || 'hash';
this.routes = options.routes || [];
// 我们这里希望传递的数组对象格式如上所示,{'/home':Home,'/about':About}
this.routesMap = this.createMap(this.routes);
// 路由中需要存放当前路径
this.history = new HistoryRoute;
this.init(); // 初始化操作
}
init(){
mode = this.mode;
if(this.mode == 'hash'){
// 先判断用户打开时有没有hash,没有的话打开#/
location.hash ? '' : location.hash = '/';
window.addEventListener('load', ()=>{
this.history.current = location.hash.slice(1)
})
window.addEventListener('hashchange', ()=>{
this.history.current = location.hash.slice(1)
})
}
else{
location.pathname ? '' : location.pathname='/';
window.addEventListener('load', ()=>{
this.history.current = location.pathname;
history.pushState({}, null, this.history.current)
})
window.addEventListener('popstate', ()=>{
this.history.current = location.pathname;
})
}
}
createMap(routes){
return routes.reduce((memo, current) => {
memo[current.path] = current.component;
return memo;
}, {})
}
go(){
}
back(){
}
push(){
}
}
// 使用Vue.use就会调用install方法
VueRouter.install = function (vue) {
// 每个组件都有this.$router或者this.$route属性
vue.mixin({
beforeCreate(){
// 获取属性名字
if(this.$options && this.$options.router){
// 定位根组件,其实就是main.js里面定义的
this._root = this;
this._router = this.$options.router; // 把router实例挂载到_router上
vue.util.defineReactive(this,'xxx',this._router.history); // this.xxx = this._router.history
}
else{
// 非根组件(渲染顺序父-> 子 -> 孙子)
this._root = this.$parent._root; // 如果想获取唯一路由
}
Object.defineProperty(this,'$router',{
get(){
return this._root._router
}
})
Object.defineProperty(this,'$route',{
get(){
// 当前的路由所在的状态
return this._root._router.history.current
}
})
}
})
vue.component('router-link',{
props:{
to:String,
tag:{
type:String,
default:'a'
}
},
render(h){
//let mode = this.mode;
// return <this.tag rel="external nofollow" href={mode === 'hash' ? `#${this.to}` : this.to}>{this.$slots.default}</this.tag>
if(mode == 'hash'){
return h('a', {attrs: {href: '#'+this.to}}, this.$slots.default)
}
else{
return h('a', {attrs: {href: this.to}}, this.$slots.default)
}
}
})
vue.component('router-view',{
// 根据当前{'about':About}得到组件
render(h){
let current = this._self._root._router.history.current;
let routesMap = this._self._root._router.routesMap;
return h(routesMap[current])
}
})
}
export default VueRouter;
index.js
import VueRouter from './vue-router';
import routes from './routes'
import Vue from 'vue';
Vue.use(VueRouter);
export default new VueRouter({
mode:'history',
routes:routes
})