apicloud与vue.js的结合

Posted 杰杰小公举

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了apicloud与vue.js的结合相关的知识,希望对你有一定的参考价值。

1.利用vue.js渲染数据

//在win获取服务器数据apiready = function() {var headerH = $api.fixStatusBar($api.dom('header'));var footerH = $api.fixTabBar($api.dom('footer'));category(frame,headerH,footerH,api);}//从自己服务器查找分类数据function category(frame,headerH,footerH,api){api.ajax({url: 'https://www.zhuzones.top/index/index/category',method: 'get',headers: {'Content-Type': 'application/json;charset=utf-8'},dataType:"json",cache:false,//(可选项)是否缓存,若缓存,下次没网络时请求则会使用缓存,仅在get请求有效data:{}}, function(ret, err) {if (ret.code == 200) {//获取到数据打开分类Frame,并且将获取的数据传到分类frameOpenNewFrame(frame,headerH,footerH,api,ret.category);} else {api.toast({msg:'获取数据失败'});}});}//打开Framefunction OpenNewFrame(frame_type,headerH,footerH,api,data=''){if(frame_type == 'slidLayout'){frame_type = 'main';}api.openFrame({name: ''+frame_type+'_frame',url: './'+frame_type+'_frame.html',bounces: true,rect: {marginTop: headerH,marginBottom: footerH,w: 'auto'},animation:{type:"movein",subType:"from_right",duration:300},progress:{type:'page',title:'请稍等...',text:'努力加载中...',color:'#FFF',height:3},pageParam:{data:data}});}//在分类frame页面获取数据//引入vue.min.js <script type="text/javascript" src="../script/vue.min.js"></script>//html 用vue进行数据渲染<div class="ind-nav ind-nav1" v-for="(item,index) in sites"><div class="ind-tit"><h2>{{item.name}}</h2></div><ul class="clearfix"><li v-for="(ite,index) in item.children_category"><div><a href="#" onclick="OpenNewWin('floor',$api.fixStatusBar($api.dom('header')),$api.fixTabBar($api.dom('footer')),api)"><i><img src="../image/wyaz.png"></i><em>{{ite.name}}</em></a></div></li></ul></div><script>apiready = function(){//获取win传过来的数据var category = api.pageParam.data;new Vue({el: '#container',data: {sites: category}});};</script>

2.开发过程中有很多重复的代码,我们这个时候就会想,搞个模板,直接引入,可以减少很多代码量,并且开发效率高.apicloud引入html模板的方法

//以底部导航栏为例//建立一个footer_frame.html模板<footer class="footer" id="footer"><ul class="footnav box-flex"><li class="on"><a href="javascript:void(0)" class="home" onclick="OpenNewWin('slidLayout',$api.fixStatusBar($api.dom('header')),$api.fixTabBar($api.dom('footer')),api);"><i></i><span class="full-block">首页</span></a></li><li><a href="javascript:void(0)" class="foot-worker" onclick="OpenNewWin('worker',$api.fixStatusBar($api.dom('header')),$api.fixTabBar($api.dom('footer')),api);"><i></i><span class="full-block">工人入驻</span></a></li><li><a href="javascript:void(0)" class="foot-order" onclick="OpenNewWin('order',$api.fixStatusBar($api.dom('header')),$api.fixTabBar($api.dom('footer')),api);"><i></i><span class="full-block">订单</span></a></li><li><a href="javascript:void(0)" class="my" onclick="OpenNewWin('my',$api.fixStatusBar($api.dom('header')),$api.fixTabBar($api.dom('footer')),api);"><i></i><span class="full-block">我的</span></a></li></ul></footer>

在要用到该模板的页面引入

<include file="html/footer_frame.html" />/**使用 apicloud 实现 include 功能参数 api 为 apiready = function() {...} 的代码块里的 api**/function include_files(api){$("include").each(function() {var ele = $(this);var file_name = ele.attr("file");var wgtRootDir = api.wgtRootDir; //程序运行目录var file_path = wgtRootDir + "/" + file_name; //拼接文件的完整路径api.readFile({path: file_path}, function(ret, err) {if (ret.status) {var file_data = ret.data;$(file_data).appendTo(ele); //把文件内容添加到 include 标签后面} else {alert(err.msg);}})})}

3.apicloud实现跟美团一样的定位功能

//main.html<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width" /><meta name="format-detection" content="telephone=no, email=no, date=no, address=no"><title>首页</title><link rel="stylesheet" type="text/css" href="../css/api.css" /><link rel="stylesheet" type="text/css" href="../css/base.css"><link rel="stylesheet" type="text/css" href="../css/common1.css"><script type="text/javascript" src="../script/jquery.min.js" ></script><script src="../script/common.js"></script><!--banner 脚本--><script src="../script/TouchSlide.1.1.js"></script><!--banner 脚本--></head>
<body><header id="header"><div class="header-bot-item"><span class="menu" tapmode onclick="openSlide()"></span><em id="city" tapmode onclick="fnOpenCitySelectorFrame();">铜陵</em><h2>预约网</h2><span class="tel"></span></div></header><footer class="footer" id="footer"><ul class="footnav box-flex"><li class="on"><a href="javascript:void(0)" class="home" onclick="OpenNewWin('slidLayout',$api.fixStatusBar($api.dom('header')),$api.fixTabBar($api.dom('footer')),api);"><i></i><span class="full-block">首页</span></a></li><li><a href="javascript:void(0)" class="foot-worker" onclick="OpenNewWin('worker',$api.fixStatusBar($api.dom('header')),$api.fixTabBar($api.dom('footer')),api);"><i></i><span class="full-block">工人入驻</span></a></li><li><a href="javascript:void(0)" class="foot-order" onclick="OpenNewWin('order',$api.fixStatusBar($api.dom('header')),$api.fixTabBar($api.dom('footer')),api);"><i></i><span class="full-block">订单</span></a></li><li><a href="javascript:void(0)" class="my" onclick="OpenNewWin('my',$api.fixStatusBar($api.dom('header')),$api.fixTabBar($api.dom('footer')),api);"><i></i><span class="full-block">我的</span></a></li></ul></footer></body><script type="text/javascript" src="../script/api.js"></script><script type="text/javascript" src="../script/SHA1.js"></script><script type="text/javascript" src="../script/public.js"></script><script type="text/javascript">var headerH,bMap,city,footerH;apiready = function() {headerH = $api.fixStatusBar($api.dom('header'));footerH = $api.fixTabBar($api.dom('footer'));//getuserinfo();
// 初始化事件监听initEventListenner(api);// 获取当前的位置信息initLocation();// 从缓存中获取上一次选择的城市信息var currentCity = $api.getStorage('currentCity');// 如果获取不到,说明还没有选择城市,打开城市选择Frame,并返回if (!currentCity) {fnOpenCitySelectorFrame();return;}// 更新界面上显示的城市名称updateCityName(currentCity.name);closeapp();};
function updateCityName(cityName_) {city = $api.byId('city');city.innerHTML = cityName_}
// 初始化事件监听function initEventListenner(api) {// 监听城市切换事件(自定义事件)api.addEventListener({name: 'cityChange'}, function(ret, err) {if (ret) {// 更新城市名称updateCityName(ret.value.currentCity.name);//打开所有的framecategory(api.winName,headerH,footerH,api);}});}
function initLocation() {// 加载百度地图模块bMap = api.require('bMap');// 获取当前经纬度bMap.getLocation({accuracy: '100m', // 定位所在城市信息,不需要精准定位autoStop: true, // 定位到经纬度后,立即自动停止定位服务filter: 100000 // 基本无需处理位置更新的情况}, function(ret, err) {if (ret.status) {// 根据经纬度获得城市名称fnGetCityNameFromLocation(ret);} else {alert(err.code);}});}// 根据经纬度获得城市名称function fnGetCityNameFromLocation(location_) {bMap.getNameFromCoords({lon: location_.lon,lat: location_.lat}, function(ret, err) {if (ret.status) {// 判断当前所在的城市与上一次选择的城市是否一致fnCheckCityChange(ret.city);}});}// 判断当前所在的城市与上一次选择的城市是否一致,不一致则打开城市选择Framefunction fnCheckCityChange(cityName_) {if (!city) {return;}if (city.innerHTML != cityName_) {fnOpenCitySelectorFrame();}else{category(api.winName,headerH,footerH,api);}    }// 打开城市选择Framefunction fnOpenCitySelectorFrame() {// 根据UI架构设计(ui-architecture.xmind),打开城市选择Frameapi.openFrame({name: 'cityselector_frame',url: './cityselector_frame.html',bgColor: 'rgba(0, 0, 0, 0.8)',rect: {x: 0,y: headerH,w: 'auto', // 自动填充所在Window的宽度h: 'auto' // 自动填充所在Window的高度},bounces: true // 打开弹动});}function category(frame,headerH,footerH,api){//从自己服务器查找数据api.ajax({url: 'https://www.zhuzones.top/index/index/category',method: 'get',headers: {'Content-Type': 'application/json;charset=utf-8'},dataType:"json",cache:false,//(可选项)是否缓存,若缓存,下次没网络时请求则会使用缓存,仅在get请求有效data:{}}, function(ret, err) {if (ret.code == 200) {OpenNewFrame(frame,headerH,footerH,api,ret.category);} else {api.toast({msg:'获取数据失败'});}});}
function closeapp(){var ci = 0;var time1, time2;api.addEventListener({name:'keyback'},function(ret, err){if( ret ){if (ci == 0){time1 = new Date().getTime();ci = 1;api.toast({msg:'再按一次返回键退出'});}else if (ci == 1) {time2 = new Date().getTime();if (time2 - time1 < 3000) {api.closeWidget({id: api.appId,retData: {name: 'closeWidget'},silent: true});}else{ci = 0;api.toast({msg:'再按一次返回键退出'});}}}});}function openSlide () {api.openSlidPane ({type: 'left'});}
function getuserinfo(){//从自己服务器查找数据api.ajax({url: 'https://www.zhuzones.top/index.php',method: 'get',headers: {'Content-Type': 'application/json;charset=utf-8'},dataType:"json",cache:false,//(可选项)是否缓存,若缓存,下次没网络时请求则会使用缓存,仅在get请求有效data:{}}, function(ret, err) {if (ret) {api.alert({msg: JSON.stringify(ret)});} else {api.alert({msg: JSON.stringify(err)});}});}</script></html>
//cityselector_frame.html<!DOCTYPE HTML><html><head><meta charset="utf-8"><meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" /><meta name="format-detection" content="telephone=no,email=no,date=no,address=no"><title>城市选择Frame</title><link rel="stylesheet" type="text/css" href="../css/api.css" /><script type="text/javascript" src="../script/vue.min.js"></script><script type="text/javascript" src="../script/jquery.min.js" ></script><style>html,body {height: 100%;background-color: transparent;}
header {width: 100%;height: 96px;}
header .title {box-sizing: border-box;width: auto;height: 96px;margin: 0 32px;padding-top: 64px;padding-bottom: 16px;border-bottom: 2px solid #c8026f;color: #fff;font-size: 14px;text-align: center;}header .title input{box-sizing: border-box;width: auto;height: 20px;bottom: 0px;color: #fff;font-size: 14px;text-align: center;border: none;outline: none;}
section {width: 100%;height: auto;}
.city {width: 100%;height: 55px;line-height: 55px;text-align: center;font-size: 22px;color: #fff;}
.highlight {opacity: 0.7;}</style></head>
<body><header><div class="title"><input type="text" name="search" placeholder="输入所需服务的地区"></div></header><section id="list"><!-- <div class="city" tapmode onclick="fnSelectCity();">{{s.name}}</div> --></section></body><script type="text/javascript" src="../script/api.js"></script><script type="text/javascript">apiready = function() {fnGetCityList(1,'');};
var cityList;var check_length = 0;function fnGetCityList(length,input_value) {if(length>0&&check_length!=length){check_length==length;$api.html($api.byId('list'),'');var params = {limit:10,keywords:input_value};api.ajax({url: 'https://www.zhuzones.top/index/index/city',method: 'get',headers: {'Content-Type': 'application/json;charset=utf-8'},dataType:"json",cache:false,//(可选项)是否缓存,若缓存,下次没网络时请求则会使用缓存,仅在get请求有效data:{values:params}}, function(ret, err) {if (ret) {// console.log($api.jsonToStr(ret));cityList = ret.city;fnUpdateCityList(ret.city);} else {api.toast({msg:'获取数据失败'});}});}}
function fnUpdateCityList(data_) {var list = $api.byId('list');var html = '';for (var i = 0; i < data_.length; i++) {if (data_[i].name) {html += '<div class="city" tapmode onclick="fnSelectCity(' + i + ');">' + data_[i].name + '</div>';}}$api.html(list, html);}
function fnSelectCity(index_) {$api.setStorage('currentCity', cityList[index_]);api.sendEvent({name: 'cityChange',extra: {currentCity: cityList[index_]}});api.setFrameAttr({hidden: true});}
//键盘弹起事件 ajax实时搜索 只限中文和数字$('input[name=search]').keyup(function(){var patt = new RegExp(/[^\x00-\xff]/ig);var length = getByteLen($(this).val().trim());if(patt.test($(this).val()) || !isNaN($(this).val())){fnGetCityList(length,$(this).val());}});
//判断是否为中文,返回长度function getByteLen(val) {var len = 0;for (var i = 0; i < val.length; i++) {varpatt = new RegExp(/[^\x00-\xff]/ig);vara = val[i];if(patt.test(a)){len += 2;}else{//len += 1;}}return len;}</script></html>

如果你选的城市与你当前城市相同,则不会再次弹出cityselectframe

效果如下:

可扫下面二维码下载app体验

我是杰杰小公举,我是一个致力于学习前端和后端开发的码农,加油


以上是关于apicloud与vue.js的结合的主要内容,如果未能解决你的问题,请参考以下文章

低代码开发的前后端联调——APICloud Studio 3 API管理工具结合数据云3.0使用教程

使用带有渲染功能的 Vue.js 3 片段

如何将 Vue.js 与 Flask 结合使用?

05.vue中js动画与Velocity.js的结合

如何将课程与有条件的课程结合起来? Vue.js 2

Vue中的JS与Velocity.js的结合