vue-router的简单实现原理
Posted l8l8
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue-router的简单实现原理相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> </head> <body> <a href="#/a">aaa</a> <a href="#/b">bbb</a> <a href="#/c">ccc</a> <div id="box"> </div> <script> let routes = [{ path: ‘/a‘, component: ‘./tem/a.html‘, childre:[ { path:"b", component:‘./img/off.png‘ } ] }, { path: ‘/b‘, component: ‘./tem/b.html‘ }, { path: ‘/c‘, component: ‘./tem/c.html‘ }, ] let cache = {}; // 建立缓存 addEventListener(‘hashchange‘, () => { let hash = location.hash.replace(‘#‘, ‘‘) // 拿到hash值 let flag = routes.some((item) => { if (item.path === hash) { if (cache[hash]) { $(‘#box‘).html(cache[hash]); } else { $.ajax(item.component).then((res) => { cache[hash] = res; $(‘#box‘).html(res); }) } return true; } return false; }) if(!flag){ $(‘body‘).html(‘404‘) } }) </script> </body> </html>
以上是关于vue-router的简单实现原理的主要内容,如果未能解决你的问题,请参考以下文章