文章内容输出来源:拉勾教育大前端高薪训练营
代码仓库地址:
https://gitee.com/jiailing/lagou-fed/tree/master/fed-e-task-03-01/code/06-my-vue-router
vue-router核心代码:
App.vue
<template>
<div id="app">
<div id="nav">
<router-link to="/">Homerouter-link> |
<router-link to="/ablout">Aboutrouter-link>
div>
<router-view/>
div>
template>
router/index.js
// 注册插件
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
}
]
const router = new VueRouter({
routes
})
export default router
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
const vm = new Vue({
router,
render: h => h(App)
}).$mount('#app')
console.log(vm)
router/index.js
const routes = [
{
path: '/',
name: 'Index',
component: Index
},
{
path: '/detail/:id',
name: 'Detail',
// 开启props,会把URL中的参数传递给组件
props: true,
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/Detail.vue')
}
]
view/Detail.vue
<template>
<div>
这是Detail页面
通过当前路由规则获取:{{ $route.params.id }}
<br>
通过开启props获取: {{ id }}
div>
template>
<script>
export default {
name: 'Detail',
// 将路由参数配置到props中
props: ['id']
}
script>
router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../components/Layout.vue'
import Login from '../views/Login.vue'
import Index from '../views/Index.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/login',
name: 'login',
component: Login
},
// 嵌套路由
{
path: '/',
component: Layout,
children: [
{
path: '',
name: 'index',
component: Index
},
{
path: 'detail/:id',
name: 'detail',
props: true,
component: () => import('@/views/Detail.vue')
}
]
}
]
const router = new VueRouter({
routes
})
export default router
components/Layout.vue
<template>
<div>
<div>
<img width='80px' src='@/assets/logo.png'>
div>
<div>
<router-view>router-view>
div>
<div>
Footer
div>
div>
template>
View/Index.vue
<template>
<div>
<router-link to="/">首页router-link>
<button @click="replace"> replace button>
<button @click="goDetail"> Detail button>
div>
template>
<script>
export default {
name: 'Index',
methods: {
replace () {
this.$router.replace('/login')
},
goDetail () {
this.$router.push({ name: 'Detail', params: { id: 1 } })
}
}
}
script>
View/Detail.vue
<template>
<div>
这是Detail页面
路由参数: {{ id }}
<button @click="go"> go(-2) button>
div>
template>
<script>
export default {
name: 'Detail',
// 将路由参数配置到props中
props: ['id'],
methods: {
go () {
this.$router.go(-2)
}
}
}
script>
History需要服务器的支持
单页应用中,服务端不存在http://www.test.com/login这样的地址会返回找不到该页面
在服务端应该除了静态资源外都返回单页应用的index.html
Node.js服务器配置
const path = require('path')
// 导入处理 history 模式的模块
const history = require('connect-history-api-fallback')
// 导入 express
const express = require('express')
const app = express()
// 关键:注册处理 history 模式的中间件
app.use(history())
// 处理静态资源的中间件,网站根目录 ../web
app.use(express.static(path.join(__dirname, '../web')))
// 开启服务器,端口是 3000
app.listen(3000, () => {
console.log('服务器开启,端口:3000')
})
Nginx服务器配置
# 启动
start nginx
# 重启
nginx -s reload
# 停止
nginx -s stop
nginx.conf
http: {
server: {
location / {
root html;
index index.html index.htm;
# 尝试查找,找不到就回到首页
try_files $uri $uri/ /index.html;
}
}
}
Vue的构建版本
运行时版:不支持template模板,需要打包的时候提前编译
完整版:包含运行时和编译器,体积比运行时版本大10k左右,程序运行的时候把模板转换成render函数
在项目根目录下增加一个文件:vue.config.js
module.exports = {
// 完成版本的Vue(带编译器版)
runtimeCompiler: true
}
最终代码:
Vuerouter/index.js
let _Vue = null
export default class VueRouter {
static install (Vue) {
// 1. 判断当前插件是否已经被安装
if (VueRouter.install.installed) return
VueRouter.install.installed = true
// 2. 把Vue构造函数记录到全局变量
_Vue = Vue
// 3. 把创建Vue实例时候传入的router对象注入到Vue实例上
// 混入
_Vue.mixin({
beforeCreate () {
if (this.$options.router) {
_Vue.prototype.$router = this.$options.router
this.$options.router.init()
}
}
})
}
constructor (options) {
this.options = options
this.routeMap = {}
// _Vue.observable创建响应式对象
this.data = _Vue.observable({
current: '/'
})
}
init () {
this.createRoutMap()
this.initComponents(_Vue)
this.initEvent()
}
createRoutMap () {
// 遍历所有的路由规则,把路由规则解析成键值对的形式,存储到routeMap中
this.options.routes.forEach(route => {
this.routeMap[route.path] = route.component
})
}
initComponents (Vue) {
Vue.component('router-link', {
props: {
to: String
},
render (h) {
return h('a', {
attrs: {
href: this.to
},
// 事件
on: {
click: this.clickHandler
}
}, [this.$slots.default])
},
methods: {
clickHandler (e) {
history.pushState({}, '', this.to)
this.$router.data.current = this.to
e.preventDefault()
}
}
// template: ' '
})
const self = this
Vue.component('router-view', {
render (h) {
const component = self.routeMap[self.data.current]
return h(component)
}
})
}
initEvent () {
window.addEventListener('popstate', () => {
this.data.current = window.location.pathname
})
}
}
Router/index.js
// ....
import VueRouter from '../vuerouter'
// ....