Fácil VueRouter lograr

Ver Router

Vue Router es VueJS gestor de ruta oficial. It VueJS y la profundidad del núcleo de la integración, de manera que las aplicaciones se vuelven fáciles de construir una sola página

el modo de enrutamiento para lograr basado en Hash

kRouter.js

import Vue from 'vue'
import Home from '../views/Home.vue'
import About from '../views/About.vue'

class VueRouter {
  constructor (options) {
    this.$options = options
    this.routeMap = {}
    // 引用Vue中数据的响应式  当路由发生改变重新去渲染页面
    this.app = new Vue({
      data: {
        current: '/'
      }
    })
  }

  init () {
    // 监听URL的变化
    this.bindEvents()
    // 解析路由配置
    this.createRouteMap(this.$options)
    //  实现两个组件
    this.initComponent()
  }

  bindEvents () {
    window.addEventListener('load', this.onHashChange.bind(this))
    window.addEventListener('hashchange', this.onHashChange.bind(this))
  }

  onHashChange () {
    // console.log(window.location.hash)  #/home
    this.app.current = window.location.hash.slice(1) || '/'
  }

  createRouteMap (options) {
    options.routes.forEach(item => {
    // {'/':Home,'/about':About}
      this.routeMap[item.path] = item.component
    })
  }

  initComponent () {
    // <router-link>home</router-link>
    Vue.component('router-link', {
      props: { to: String },
      render (h) {
      	// this.$slots.default 存储了当前元素的子节点
        return h('a', { attrs: { href: '#' + this.to } }, [
          this.$slots.default
        ])
      }
    })
    // router-view
    Vue.component('router-view', {
      render: h => {
        const comp = this.routeMap[this.app.current]
        return h(comp)
      }
    })
  }
}
// 入参是Vue构造函数
VueRouter.install = function (Vue) {
  // 混入
  Vue.mixin({
    beforeCreate () {
      // this.$options 表示new VUe({})实例中的配置项
      // this 是 当前的Vue实例
      if (this.$options.router) {
        // 仅在根组件中执行一次
        // 后面的组件中都可以使用this.$router
        Vue.prototype.$router = this.$options.router
        this.$options.router.init()
      }
    }
  })
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
]

const router = new VueRouter({
  routes
})

export default router

1, la creación de VueRouterclase tiempo necesita implementar installun método para usar VueRoutercomo un VueJSplug-in para el uso. VueRouterSe añadió como un tapón utilizado, a través mixinde un efecto mixto de cada Vueinstanciación, la inicialización se completará en el router cuando ganchos beforeCreate, e inicializa sólo una vez.
2, VueRouterhay tres método núcleo

  • URL monitor cambia
    por escuchar el cambio de la URL, para encontrar el componente correspondiente prestación
  • Enrutamiento de configuración de análisis
    de la URL al mapa a un componente objeto
  • Construcción de dos componentes
    hacen componente (vista-router) de salto de página de montaje (Ver-Link)
    . 3, renderla función de representación

En pocas palabras, se utiliza la plantilla en la sintaxis Vue HTML para crear una página, utilice la función que podemos utilizar para construir JS DOM lenguaje render. Debido Vue es un DOM virtual, así que para obtener la plantilla cuando la plantilla se tradujo también en una función vnode, y la función de representar con una función DOM, Vue en la eliminación del proceso de traducción

render: h => {	
        const comp = this.routeMap[this.app.current]
        return h(comp)
      }

Aquí vamos a componentes ruta coincidente, prestados por VNode función de render.

modo HTML5History Basado

import Vue from 'vue'
import Home from '../views/Home.vue'
import About from '../views/About.vue'

class VueRouter {
  constructor (options) {
    this.$options = options
    this.routeMap = {}
    // 引用Vue中数据的响应式  当路由发生改变重新去渲染页面
    this.app = new Vue({
      data: {
        current: '/'
      }
    })
  }

  init () {
    // 监听URL的变化
    this.bindEvents()
    // 解析路由配置
    this.createRouteMap(this.$options)
    //  实现两个组件
    this.initComponent()
  }

  bindEvents () {
    window.addEventListener('load', this.onHashChange.bind(this))
    window.addEventListener('hashchange', this.onHashChange.bind(this))
  }

  onHashChange () {
    this.app.current = window.location.pathname || '/'
  }

  createRouteMap (options) {
    options.routes.forEach(item => {
    // {'/':Home,'/about':About}
      this.routeMap[item.path] = item.component
    })
  }

  initComponent () {
    // <router-link>home</router-link>
    Vue.component('router-link', {
      props: { to: String },
      render (h) {
        return h('a', { attrs: { href: this.to } }, [
          this.$slots.default
        ])
      }
    })
    // router-view
    Vue.component('router-view', {
      render: h => {
        const comp = this.routeMap[this.app.current]
        return h(comp)
      }
    })
  }
}
// 入参是Vue构造函数
VueRouter.install = function (Vue) {
  // 混入
  Vue.mixin({
    beforeCreate () {
      // this.$options 表示new VUe({})实例中的配置项
      // this 是 当前的Vue实例
      if (this.$options.router) {
        // 仅在根组件中执行一次
        // 后面的组件中都可以使用this.$router
        Vue.prototype.$router = this.$options.router
        this.$options.router.init()
      }
    }
  })
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
]

const router = new VueRouter({
  routes
})

export default router

representaciones

Aquí Insertar imagen Descripción

Publicado 17 artículos originales · ganado elogios 0 · Vistas 394

Supongo que te gusta

Origin blog.csdn.net/k19970320j/article/details/104456940
Recomendado
Clasificación