Warehouse address: gitee.com/littleboyck…
File location: Router folder
<div><a r-link="#/home">Home page</a></div>
<div><a r-link="#/button">Button component</a></div>
<div><a r-link="#/form">Form components</a></div>
<div id="app"></div>
Copy the code
class Router{
constructor(){
// Cache route data
this.routes = {};
this.ready();
}
static isDOM(el){
el = Array.from(el);
if(el.length == 0) {return false; }for(let i = 0,len=el.length; i<len; i++){
if(el[i].nodeType ! = (Node.ELEMENT_NODE||Node.DOCUMENT_NODE)){return false; }}return true;
}
static getEl(selector){
if(selector.nodeType ! = (Node.ELEMENT_NODE||Node.DOCUMENT_NODE)){if(/^#[^#\s\b]+$/.test(selector)){
selector = document.querySelector(selector)
}else{
selector = document.querySelectorAll(selector)
}
}
return selector;
}
static evtListener(el,event,handle){
el = Router.isDOM(el) ? [...el] : [el];
el.forEach(el= >el.addEventListener(event,handle));
}
static removeListener(el,event,handle){
el = Router.isDOM(el) ? [...el] : [el];
el.forEach(el= >el.removeEventListener(event,handle));
}
static xhr(options){}static isHash(val){
return /^#[^\s\b]+$/.test(val)
}
static setTitle(htmlString){
let result = /<title>([\w\W]*)<\/title>/.exec(htmlString)
,title = result ? result[1] : htmlString;
//,matches = document.querySelectorAll('title')[0].textContent.match(/^{{([^{}]+)}}$/);
document.querySelectorAll('title') [0].textContent = title
}
/ / collection routes
route(path,callback){
this.routes[path] = callback ? callback : function(){};
}
// Redirection changes the hash
redirect(path){ location.hash ! = path && (location.hash = path) }// The jump is internal and does not change the hash
forward(path){
this.routes[path] && this.routes[path].call(this)}init(firstPath){
let curHash = location.hash;
curHash && (firstPath = curHash)
Router.isHash(firstPath) && (location.hash = firstPath) && curHash && this.forward(firstPath)
}
/ / monitoring hashchange
listenerHashchange(){
Router.evtListener(window.'hashchange'.() = >{
this.forward(location.hash)
});
}
/ / initialization
ready(){
this.listenerHashchange(); }}Copy the code
use
const router = new Router()
// add the routes dependency
router.route("#/home".function(){
Router.setTitle("Home page")
document.getElementById('content').innerHTML = 'Welcome to the home page'
})
router.route("#/button".function(){
$.ajax({
type:'get'
,url:'.. /component/button.html'
}).then(function(html){
Router.setTitle(html)
document.getElementById('content').innerHTML = html;
})
})
router.route("#/form".function(){
$.ajax({
type:'get'
,url:'.. /component/element.html'
}).then(function(html){
Router.setTitle(html)
document.getElementById('content').innerHTML = html; })})//2. Initialize default page
router.init('#/home')
//3. Click events
Router.evtListener(document.querySelectorAll('[r-link]'),'click'.function (e) {
router.redirect(this.getAttribute('r-link'))})Copy the code