使用步骤
1.创建router对象,router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
// 路由组件
import index from '@/views/index'
// 组成插件
Vue.use(VueRouter)
// 路由规则
const routes = [{ name: 'index', path: '/', component: index }]
// 路由对象
const router = new VueRouter({ routes })
export default router
2.注册router 对象, main.js
import router from './router'
new Vue({
  render: (h) => h(App),
  router,
}).$mount('#app')
3.创建路由组件站位,App.vue
<router-view></router-view>
4.创建链接
<router-link to="./">首页</router-link> 
<router-link :to="{name: 'index'}">首页</router-link>
动态路由传参
const routes = [
  {
    name: 'detail',
    // 路径中携带参数
    path: '/detail/:id',
    component: detail,
  },
] 
// detail 组件中接收路由参数
$route.params.id
const routes = [
  {
    name: 'detail',
    // 路径中携带参数
    path: '/detail/:id',
    component: detail,
    props: true,
  },
]
// detail 组件中接收路由参数
const detail = {
  props: ['id'],
  template: '<div>Detail ID: {{ id }}</div>',
}
嵌套路由
index组件和details组件嵌套layout组件
{ 
  path: '/',
  component: layout, 
  children: [ 
    { 
      name: 'index', 
       path: '/', 
       component: index 
    },{ 
      name: 'details', 
      path: '/details/:id', 
      component: details 
    } 
  ] 
}
编程式导航
// 跳转到指定路径 
router.push('/login')
 // 命名的路由
router.push({ name: 'user', params: { id: '5' }}) router.replace() 
router.go()
Hash 模式 和 History 模式的区别
- 表现形式的区别
 - 原理区别
- hash模式
Vue Router 默认使用的是hash模式,使用hash模式来模拟一个完整的URL,通过onhashchange监听路径的变化 
 - hash模式
 - hsitory模式
基于History API 
history.pushState() 
history.replaceState()
history.go()
- 开启History模式
 
const router = new VueRouter({ 
// mode: 'hash',
 mode: 'history',
 routes 
})
HTML5 History模式的使用
- History需要服务器的支持
 - 单页应用中,服务端不存在 http://www.testurl.com/login 这样的地址会返回找不到该页面
 - 在服务端应该除了静态资源外都返回单页应用的index.html
 
node.js环境
- 示例演示
 
nginx环境配置
- 从官网下载nginx的压缩包
 - 把压缩包解压到c盘的根目录
 - 修改conf/nginx.conf文件
 
location / { 
  root html; 
  index index.html index.htm; 
  #新添加内容 
  #尝试读取$uri(当前请求的路径),如果读取不到 
读取$uri/这个文件夹下的首页 
  #如果都获取不到返回根目录中的 index.html 
  try_files $uri $uri/ /index.html; }
- 打开命令行,切换到nginx目录
 - nginx启动,重启和停止
 
#启动
start nginx
#重启
nginx -s reload
# 停止
nginx -s stop
Vue Router 模拟实现
- 前置的知识:
插件、slot插槽、混入、render函数、运行时和完整版的Vue - 回顾Vue Router的核心代码
 
// 注册插件 
// Vue.use() 内部调用传入对象的 install 方法
Vue.use(VueRouter) 
// 创建路由对象 
const router = new VueRouter({ 
  routes: [ 
    { name: 'home', path: '/', component: homeComponent } 
  ] 
})
// 创建 Vue 实例,注册 router 对象 
new Vue({ 
  router, 
  render: h => h(App) 
}).$mount('#app')
实现思路
- 创建LVueRouter插件,静态方法install
1.判断插件是否已经被加载
2.当Vue加载的时候把传入的router对象挂载到Vue实例上(注意:只执行一次) - 创建LVueRouter类
1.初始化options、routeMap、app(简化操作,创建 Vue 实例作为响应式数据记录当前路
径)
2.initRouteMap() 遍历所有路由信息,把组件和路由的映射记录到 routeMap 对象中
3.注册 popstate 事件,当路由地址发生变化,重新记录当前的路径
4.创建 router-link 和 router-view 组件
5.当路径改变的时候通过当前路径在 routerMap 对象中找到对应的组件,渲染 router-view 
代码实现
- 创建LVueRouter插件
 
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.prototype.$router = this.$options.router
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
        }
      },
    })
  }
}
- LVueRouter 类 - 构造函数
 
  //构造函数
  constructor(options) {
    this.options = options
   // 记录路径和对应的组件
    this.routeMap = {}
    // observable
    this.data = _Vue.observable({
      //存储当前路由地址
      current: '/',
    })
    this.init()
  }
- 实现 LVueRouter 类 - initRouteMap()
 
  createRouteMap() {
    //遍历所有的路由规则 吧路由规则解析成键值对的形式存储到routeMap中
    this.options.routes.forEach((route) => {
      // 记录路径和组件的映射关系
      this.routeMap[route.path] = route.component
    })
  }
- 实现 LVueRouter 类 - router-link 和 router-view 组件
 
  initComponent(Vue) {
    Vue.component('router-link', {
      props: {
        to: String,
      },
      // 需要带编译器版本的 Vue.js
      // template: "<a :href='\"#\" + to'><slot></slot></a>"
      // 使用运行时版本的 Vue.js
      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='to'><slot></slot><>"
    })
- 实现 LVueRouter 类 - 注册事件
 
  initEvent() {
    //
    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname
    })
  }
- 实现 LVueRouter 类 - init()
 
  init() {
    this.createRouteMap()
    this.initComponent(_Vue)
    this.initEvent()
  }
完整代码
console.dir(Vue)
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.prototype.$router = this.$options.router
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
        }
      },
    })
  }
  //构造函数
  constructor(options) {
    this.options = options
    // 记录路径和对应的组件
    this.routeMap = {}
    // observable
    this.data = _Vue.observable({
      //存储当前路由地址
      current: '/',
    })
    this.init()
  }
  init() {
    this.createRouteMap()
    this.initComponent(_Vue)
    this.initEvent()
  }
  createRouteMap() {
    //遍历所有的路由规则 吧路由规则解析成键值对的形式存储到routeMap中
    this.options.routes.forEach((route) => {
      // 记录路径和组件的映射关系
      this.routeMap[route.path] = route.component
    })
  }
  initComponent(Vue) {
    Vue.component('router-link', {
      props: {
        to: String,
      },
      // 需要带编译器版本的 Vue.js
      // template: "<a :href='\"#\" + to'><slot></slot></a>"
      // 使用运行时版本的 Vue.js
      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='to'><slot></slot><>"
    })
    const self = this
    Vue.component('router-view', {
      render(h) {
        // self.data.current
        const cm = self.routeMap[self.data.current]
        return h(cm)
      },
    })
  }
  initEvent() {
    //
    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname
    })
  }
}








网友评论