一、动态路由
页面中的使用
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 }}
<!-- 方式二:路由规则中开启props传参 (推荐)-->
通过开启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>
复制代码
三、编程式导航
1. this.$router.replace(‘/login’)
this.$router.replace('/login')
replace 不带历史记录
复制代码
2. this.$router.push({ name: ‘Detail’, params: { id: 1 } })
this.$router.push(‘/’)
push带历史记录
复制代码
3. this.$router.go(-2)
go() 去那个页面
复制代码
四、Hash模式和History模式
1. 表现形式的区别
- Hash模式:http://localhost/#/detail?id=1234
- History模式:http://localhost/detail/1234
2. 原理的区别
- Hash模式是基于锚点,以及onHashChange事件。
- History模式是基于HTML5中的History API
History.pushState() IE10以后才支持
History.replaceState()
3. History模式的使用
-
History需要服务器的支持
-
单页应用中,服务端不存在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;
}
}
}
复制代码
4. Hash模式
- URL中#后面的内容作为路径地址
- 监听hashchange事件
- 根据当前路由地址找到对应组件重新渲染
5. History模式
- 通过History.pushState()方法改变地址栏(不会向服务器发送请求,但会将这次URL记录到历史中)
- 监听popstate事件
- 根据当前路由地址找到对应组件重新渲染
五、模拟实现
分析代码
- options记录传来的路由规则
- routeMap 路由地址和组件的对应关系,将来路由规则会解析到routeMap中
- data是响应式的对象,里面有current路由地址
- +是对外公开的方法 _是静态方法
install是vue的插件机制
Vue的构建版本
- 运行时版:不支持template模板,需要打包的时候提前编译使用render函数
Vue.component('router-link', {
props: {
to: String
},
render (h) {
return h('a', {
attrs: {
href: this.to
},
}, [this.$slots.default])
},
// template: '<a href="https://juejin.cn/post/to"><slot></slot></a>'
})
复制代码
- 完整版:包含运行时和编译器,体积比运行时版本大10k左右,程序运行的时候把模板转换成render函数
在项目根目录下增加一个文件:vue.config.js
module.exports = {
// 完成版本的Vue(带编译器版)
runtimeCompiler: true
}
手写vuerouter,只是模拟,不是源码
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('routeLink', {
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: '<a href="https://juejin.cn/post/to"><slot></slot></a>'
})
const self = this
Vue.component('routerView', {
render (h) {
const component = self.routeMap[self.data.current]
return h(component)
}
})
}
initEvent () {
window.addEventListener('popstate', () => {
this.data.current = window.location.pathname
})
}
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END