- main.js new Vue 中配置router
- 注入$route
- 路由规则
- 存储当前路由的数据
- 注入$router
- 路由对象
- 包括路由方法
- currentRoute获取当前的路由规则
- 路由对象
- 注入$route
- 动态路由传参
- 1.路由配置 使用/:id 站位
- 使用两种方式
- 1.直接通过当前路由规则
- 2.通过开启props:true,会将值传递给组件props中 推荐
- 编程是导航
- this.$router.push() 传入路径或name
- 传参 push({name:”123”,params:this.id})
- this.$router.replace()参数同Push replace不会记录历史
- this.go()
- this.$router.push() 传入路径或name
- hash和history模式
- hash模式带#
- hash模式基于锚点,和onhashchange事件
- history模式url不带#
- 改变浏览器地址,不发请求
- 基于html5中的historyAPI
- history.pushState() IE10之后
- history.replaceState()
- hash模式带#
- history模式使用
- 需要服务器支持
- 单页面应用中,不存在 /login这样的地址
- 在服务端配置除了静态资源外都返回单页应用外的index.html
- node中 使用 .use(history)
- nginx中
- 在server中配置
- location / 中
- try_files:$uri 查找当前文件,未找到的话把它当成目录 $uri/继续查找 未找到 /index.html返回单页面应用的首页
- location / 中
- 在server中配置
- 需要服务器支持
Vue-router的实现原理
- Hash模式
History模式
- 调用history.pushState方法改变地址栏 不发送请求,并添加到历史中
- 监听popstate事件。pushState replaceState不触发
根据地址找到组件渲染 ```javascript let _Vue = null export default class VueRouter { //静态方法,两个参数,Vue构造函数,可选参数 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 = {} //记录当前路由地址,响应式 this.data = _Vue.observable({
current: "/",
}) } init() {
this.createRouterMap() this.initComponents(_Vue) this.initEvent() } createRouterMap() { //遍历所有路由规则并将路由规则转化为键值对存储到routeMap中 this.options.routes.forEach((route) => {
this.routeMap[route.path] = route.component
}) } initComponents(Vue) { // 创建route-link组件 Vue.component(“router-link”, {
props: {
to: String,
},
// template: '<a :href="to"><slot></slot></a>',
//运行时使用render函数
render(h) {
// h创建虚拟dom,创建点击事件阻止默认事件
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()
},
},
}) 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
}) } }
```