JQuery或Zepto单页应用路由Router

  • 之前一直都是在用AngularJs在做前台开发,这几天要做移动版页面,所以前端采用了Zepto+WEUI CSS来做,主要是因为Zepto比较小巧,用起来也JQuery一样锋利。
  • 用AngularJs时我们一直都是用ui-router做单页应用,为了保持PC端和移动链接地址一致,所以移动端也要采用ui-router风格的单页应用模式。找了一圈,发现vipspa可以实现这个功能,但跟我想要的还是有点儿不一样,于是拿来小改一下,改成ui-router风格的jquery或zepto的单页应用Router插件(见附件)。
  • 这里主要介绍如何使用。
  • index.html
  • <html lang="zh-CN">
    <header>
    <meta charset="utf-8"/>
    </header>
    <body>
    	<!-- header -->
    	<header>
    		This is header.
    	</header>
    	
    	<!-- main -->
    	<div id="main">
    		<div class="ui-view"></div>
    	</div>
    	
    	<!-- footer -->
    	<footer>
    		This is footer.
    	</footer>
    	
    	<script src="static/lib/zepto/zepto.min.js" type="text/javascript"></script>
    	<script src="static/lib/vipspa/vipspa.min.js" type="text/javascript"></script>
    	<script src="static/js/index/app.js" type="text/javascript"></script>
    </body>
    </html>
    
     
  • js 文件结构


  •  app.js
  • $(function() {
    	vipspa.start({
    		view: '.ui-view',// 装载视图的dom
    		router: {
    			'/home': {
    				templateUrl: 'static/views/index/home.html',
    				controller: 'static/js/index/controllers/home.js'
    			},
    			'/content': {
    				templateUrl: 'static/views/index/content.html',
    				controller: 'static/js/index/controllers/content.js'
    			},
    			'/component/:uuid/item/:itemid': {
    				templateUrl: 'static/views/index/component.html',
    				controller: 'static/js/index/controllers/component.js'
    			},
    			'defaults': '/home'// 不符合上述路由时,默认跳至
    		},
    		errorTemplateId: '#error'
    	});
    });
     
  • 视图片段文件结构


  •  
  • 每个视图就已经与每个Controller js绑定了,没个视图的展示与操作独立开来。
  • home
  • <p>home</p>
    console.log('This is the page home.');
     
     
  • content
  • <p>content</p>
    console.log('This is the page content.');
     
  • component
  • <h3>
    这是器件页面
    器件的uuid是:<span id="uuid"></span>,id是: <span id="itemid"></span>
    </h3>
    var obj = vipspa.params;// 通过路由传递的参数
    
    $('#uuid').text(obj.uuid);// 由:uuid指定位置的参数
    $('#itemid').text(obj.itemid);// 由:itemid指定位置的参数
     
  • 效果
  • 当我们打卡index路径时,默认跳至home页面


  •  
  • 当我们进入index#/content路径是,我们可以进入content页面


  •  
  • 当我们进入index#/component/uuid001/item/item002的路径是,进入到component的页面,并获得路径中的参数


  •  这就是一个简单好用的Jquery router。

猜你喜欢

转载自qq290063295.iteye.com/blog/2316385