SPA应用 + 路由理解 + 前端路由的原理

171 阅读1分钟

SPA的理解

  1. 单页Web应用(single page web application,SPA)
  2. 整个应用只有一个完整的页面
  3. 点击页面中的链接不会刷新页面,只会做页面的局部更新。
  4. 数据都需要通过ajax请求获取, 并在前端异步展现。

路由的理解

1. 什么是路由:

  1. 一个路由就是一个映射关系(key:value)
  2. key为路径, value可能是function或component

2. 路由分类

  1. 后端路由
1 理解:value是function, 用来处理客户端提交的请求。
2 注册路由: router.get(path, function(req, res))
3工作过程:当node接收到一个请求时, 根据请求路径找到匹配的路由, 调用路由中的函数来处理请求, 返回响应数据
  1. 前端路由
1. 浏览器端路由,value是component,用于展示页面内容。
2. 注册路由: <Route path="/test" component={Test}>
3. 工作过程:当浏览器的path变为/test时, 当前路由组件就会变为Test组件

前端路由的原理

<a href="http://www.atguigu.com" onclick="return push('/test1') ">push test1</a>
<button onClick="push('/test2')">push test2</button>
<button onClick="replace('/test3')">replace test3</button>
<button onClick="back()">&lt;= 回退</button>
<button onClick="forword()">前进 =&gt;</button>
<script type="text/javascript" src="https://cdn.bootcss.com/history/4.7.2/history.js"></script>


// let history = History.createBrowserHistory() //方法一,直接使用H5推出的history身上的API
let history = History.createHashHistory() //方法二,hash值(锚点)
function push (path) {
    history.push(path)
    return false
}

function replace (path) {
    history.replace(path)
}

function back() {
    history.goBack()
}

function forword() {
    history.goForward()
}

history.listen((location) => {
    console.log('请求路由路径变化了', location)
})