SPA (单页面应用程序)

SPA 李丽红
文章标签: SPA

单页Web应用(single page web application,SPA),就是只有一张Web页面应用,是加载单个HTML 页面并在用户与应用程序交互时动态更新该页面的Web应用程序

下面示例代码实现简单单页面跳转

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="dist/style/weui.css">
<title>单页面</title>
</head>
<body>
<div class="container-fluid" id="show-all"></div>
<script type="text/html" id="login-page">
<div class="page home">
<h2>这是登录页面</h2>
<ul>
<li><a href="#enroll-page">注册</a></li>
<li><a href="#forget-password">忘记密码</a></li>
</ul>
</div>
</script>
<script type="text/html" id="enroll-page">
<div class="page">
<a href="javascript:home()">返回</a>
<h2>这是注册页面</h2>
</div>
</script>
<script type="text/html" id="forget-password">
<div class="page">
<h2>这是忘记密码页面</h2>
</div>
</script>

<script>
function Router() {
this.routes = {};
this.currentUrl = '';
}
Router.prototype.route = function(path, callback) { //route 存储路由更新时的回调到回调数组routes中,回调函数将负责对页面的更新
this.routes[path] = callback || function() {};
};
Router.prototype.refresh = function() { //refresh 执行当前url对应的回调函数,更新页面
this.currentUrl = location.hash.slice(1) || '/';
this.routes[this.currentUrl]();
};
Router.prototype.init = function() { //init 监听浏览器 url hash 更新事件
window.addEventListener('load', this.refresh.bind(this), false);
window.addEventListener('hashchange', this.refresh.bind(this), false);
};
window.Router = new Router();
window.Router.init();

var box = document.querySelector("#show-all");//获取设置好的空盒子对象
//通过路径判断要访问那个页面,就把那个页面的内容放到设置好的空盒子里面
Router.route('/', function() {
box.innerHTML = document.getElementById("login-page").innerHTML;
});
Router.route('enroll-page', function() {
box.innerHTML = document.getElementById("enroll-page").innerHTML;
});
Router.route('forget-password', function() {
box.innerHTML = document.getElementById("forget-password").innerHTML;
});
</script>
</body>
</html>

还能输出{{restrictNumber}}个字符  
  • {{reply.author}}

    {{CommonUtil.formateDate(reply.ac_CommentDate).shortTime}}
  • 回复了{{Comments.author}} :