背景:

  单页 Web 应用 (single-page application 简称为 SPA) 是一种特殊的 Web 应用,它将所有的活动均局限于一个Web页面中;这就表示Web应用被加载出来之后,Web中所有的交互和跳转均不会与服务器发生交互,而是使用JS转换HTML中的内容。

实现的原理:

  1. 使用 hashchange 可以检测路由的变化情况

  2. 使用 location.hash 路由,然后根据路由选择需要渲染的页面内容

SPA Demo:

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SPA Demo</title>
<style>
.box {
width: 300px;
height: 300px;
background: lightyellow;
margin: 0 auto;
}
.content {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="box">
<div class="content"></div>
<button>下一页</button>
</div>
<script>
const renderHtml = (text) => {
let element = document.querySelector('.content')
element.innerHTML = text
}
const responseForPath = (path) => {
let mapper = {
'/0': `<h3>第一个界面</h3>`,
'/1': `<h3>第二个界面</h3>`,
'/2': `<h3>第三个界面</h3>`,
'/3': `<h3>第四个界面</h3>`,
}
if (path in mapper) {
return mapper[path]
} else {
return 'not found'
}
}
// 获取当前的路由,然后根据路由选择需要渲染的内容
const render = () => {
console.log(location.hash)
// 根据路由选择相应的内容
let r = responseForPath(location.hash.slice(1))
// 渲染内容
renderHtml(r)
}
const bindEvents = () => {
// 给当前窗口绑定 hashchange 事件
window.addEventListener('hashchange', (event) => {
render()
})
}
// 给按钮绑定事件,实现页面路由的更换
const buttonBindEvent = () => {
let ele = document.querySelector('button')
ele.addEventListener('click', (event) => {
let x = location.hash
// console.log(x)
if (x === '') {
location.hash = '/0'
} else {
console.log(x)
let temp = x.slice(2)
console.log(temp)
temp = (Number(temp) + 1) % 4
location.hash = `/${temp}`
}
})
}
const __main = () => {
bindEvents()
render()
buttonBindEvent()
} // DOMContentLoaded 事件表示 HTML 已经加载(渲染)到页面中, 这个时候操作 DOM 元素就没有问题
document.addEventListener('DOMContentLoaded', () => {
__main()
})
</script>
</body>
</html>

参考资料:

  1.  如何快速开发SPA应用:https://www.cnblogs.com/constantince/p/5586851.html

最新文章

  1. apache+mysql+php的环境配置
  2. XP 安装不了framework 4.0 的解决方法
  3. 基于正则的INI读写工具类,支持加密解密
  4. SQL Server代理(10/12):使用代理账号运行作业
  5. The All-purpose Zero---hdu5773(LIS变形)
  6. Golang连接Oracle数据库
  7. 【HDOJ】2774 Shuffle
  8. 在XML里的XSD和DTD以及standalone的使用
  9. lucene4.0 基于smb文件服务器的全文检索
  10. HTML、CSS、JS 样式
  11. 简单五子棋,没有电脑AI
  12. NLP是什么
  13. 部署wepy框架开发微信小程序
  14. ffmpeg中av_log的实现分析
  15. 【java】static的应用场景
  16. Hadoop YARN简介
  17. String为什么不可变
  18. 面试经典问题---数据库索引B+、B-树
  19. MySQL批量添加表字段
  20. U盘kali系统安装

热门文章

  1. rsync服务端一键安装rsync脚本(非源码)
  2. C# 判断文件格式的一些总结
  3. 【Linux基础总结】Shell 基础编程
  4. Android Bluetooth How To--Based on Android L Bluedroid
  5. hadoop问题
  6. [hdu1242]优先队列
  7. C# 数据操作系列 - 6 EF Core 配置映射关系
  8. 十分钟看懂AES加密
  9. Lr运行错误Error: Socket descriptor not found. Hint: the problem might be
  10. Flutter不能做什么:局限性