vue
单页面程序
浏览器版网易音乐
局部刷新
缺点,低版本的浏览器可能无法实现
不利于SEO 搜索引擎搜索
多页面程序
全局刷新
更利于SEO
Example1
后端封装好数据接口
const todos=[ { 'id':1, 'title':"吃饭" }, { 'id':2, 'title':"吃饭2" }, ] router .get("/",(req,rep,next)=>{ rep.json(todos) }) .post("/",(req,rep,next)=>{ var todo={ title:req.body.title, id:todos[todos.length-1].id+1 } todos.push(todo) rep.json(todos) })
前端写好页面,页面中使用ajax请求接口,获取数据后将数据填充要页面中
浏览器现在访问的就直接使静态的页面了,页面中在异步请求数据接口
我把页面放在了静态资源目录下面,浏览器就可以直接访问
<body> <ul id="container"> </ul> <script id="tpl" type="text/template"> {{ each todos }} <li>{{$value}}</li> {{/each}} </script> </body> <script src="/node_modules/jquery/dist/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="/node_modules/art-template/lib/template-web.js" type="text/javascript" charset="utf-8"></script> <script> $(document).ready(function(){ $.get('/',function(data){ console.log(data); var htmlStr=template('tpl',{ todos:data }) $("#container").html(htmlStr) }) }) </script>
首先使用ajax请求数据接口,实际上就是请求地址
使用art-template将请求到的数据配置成字符串
使用jquery将模板字符串填充到对应的容器中
单页方式进行加载
使用到锚点来进行内容修改,而页面不跳转
使用window.onhashchange 监听锚点改变事件,当事件改变时进入请求
</div>
window.onhashchange=function(){ /*console.log(this.location.hash.substr(1)) *///从第二个字符串开始走,拿到路由 var hash=window.location.hash.substr(1); if(hash === "/my"){ $("#container").html("my") }else if(hash === "/frind"){ $("#container").html("friend") }else{ console.log("find") $.get("find-music.html",function(data){ $("#container").html(data) //得到find-music.html文件字符串 }) } }
当请求find时,将提前写好的find-music.html文件内容填充到容器中
填充好之后在请求对应的API!
首先填充的内容存在ID冲突,因为不同html页面是整合在一起的
<ul id="todos-container">
</ul>
<script type="text/template" id="tpl-todos">
<ul>
{{ each todos}}
<li>{{$value.title}}</li>
{{/each}}
</ul>
</script>
<script type="text/javascript">
$.get("/API",function(data){
var htmlStr=template('tpl-todos',{
todos:data
})
$("#todos-container").html(htmlStr)
})
</script>
解决单页面路由问题
<script>
$(document).ready(function(){
console.log(window.location.hash.substr(1));
route()
})
window.onhashchange=function(){
route()
}
var route=function(){
/*console.log(this.location.hash.substr(1)) *///从第二个字符串开始走,拿到路由
var hash=window.location.hash.substr(1);
if(hash === "/my"){
$("#container").html("my")
}else if(hash === "/frind"){
$("#container").html("friend")
}else if(hash === "/find"){
console.log("find")
$.get("find-music.html",function(data){
$("#container").html(data) //得到find-music.html文件字符串
})
}else{
$.get('/API',function(data){
$('#container').html(data[0].id)
console.log(data)
})
}
}
</script>
基于前端框架进行的单页操作
angular
Google
数据驱动视图模型,不操作DOM
react
Facebook
组件化
vue
尤雨溪
借鉴前者长处,后起之秀
工具
基于Chrome的vuejs.devtools插件
Last updated
Was this helpful?