Simple implementation of front-end routing

concept

The concept of routing first appeared in the background. In the web development of the traditional MVC architecture, routing rules are set in the background. When the user sends a request, the background renders the data into the template according to the set routing rules, and returns the template to the user. Therefore, the user needs to refresh the page every time a request is made, which greatly affects the interactive experience.

The emergence of ajax effectively solves this problem. Ajax (asynchronous javascript and xml), a technical solution provided by the browser, uses the method of asynchronously loading data to achieve partial page refresh, which greatly improves the user experience.

The higher version of the asynchronous interactive experience is SPA-single-page application, which not only does not refresh the page interaction, but also does not refresh between page jumps. In order to implement SPA, there is the concept of front-end routing.

accomplish

Angular, React, and Vue all have the concept of front-end routing, but how exactly is front-end routing implemented? And look at the following code:

/**
 * Created by lonelydawn on 2018-04-03.
 * javascript version: ES 6
 */

import homepage from '../views/homepage.html'
import product from '../views/product.html'
import server from '../views/server.html'

let Router = function (config) {
  config = config || {}
  // 页面容器
  let app = document.getElementById(config.el) || document.body
  let routes = Object.prototype.toString.call(config.routes) === '[object Array]'
    ? config.routes : []
  // 加载页面
  let load = function (route) {
    if (route) {
      let beforeLoad = route.beforeLoad || function () {}
      let afterLoad = route.afterLoad || function () {}
      beforeLoad()
      app.innerHTML = route.template
      afterLoad()
    }
  }
  // 根据 location 的 hash 属性实现页面切换
  let redirect = function () {
    let url = window.location.hash.slice(1) || '/'
    for (let route of routes) {
      if (url === route.url) {
        load(route)
        return
      }
    }
    load(routes[0])
  }
  // 添加路由规则
  this.push = function (route) {
    if (Object.prototype.toString.call(route) === '[object Object]') {
      routes.push(route)
    }
  }
  // 更改页面容器
  this.bind = function (el) {
    app = document.getElementById(el) || document.body
  }
  // event
  window.addEventListener('load', redirect, false)
  // 监控 hash 变化
  window.addEventListener('hashchange', redirect, false)
}
// 创建路由对象
let router = new Router()
router.bind('app')
router.push({
  url: '/',
  template: homepage
})
router.push({
  url: '/product',
  template: product
})
router.push({
  url: '/server',
  template: server
})

Example

 

source code

demo download

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324371238&siteId=291194637