如果你对该文章中的内容有疑问/不解,可以点击此处链接提问要注明问题和此文章链接地址 点击此处跳转 每个 .vue 文件最多包含一个 < template> 块。 每个 .vue 文件最多包含一个 < script> 块。 一个 .vue 文件可以包含多个 < style> 标签。 导入 < script src="./script.js"> uni-app框架目前仅支持长度单位 px 和 %。 PS:uni-app 的基准宽度为 750px。 样式导入 <code class="line-numbers"><style> @import "../../common/uni.css"; .uni-card { box-shadow: none; }</style></code> pages.json 配置(tabbar/窗口) http://www.hcoder.net/tutorials/info_1339.html 生命周期 onLoad 监听页面加载,其参数为上个页面传递的数据,参数类型为object(用于页面传参),参考示例 onShow 监听页面显示 onReady 监听页面初次渲染完成 onHide 监听页面隐藏 onUnload 监听页面卸载 onPullDownRefresh 监听用户下拉动作 onReachBottom 页面上拉触底事件的处理函数 onShareAppMessage 用户点击右上角分享 微信小程序 onPageScroll 监听页面滚动 onTabItemTap 当前是 tab 页时,点击 tab 时触发。 数据绑定 <code class="line-numbers">data: { title: 'Hello', name : 'hcoder' }, ..... <text class="title">{{title}}</text></code> 列表渲染 <code class="line-numbers"><view v-for="(item, index) in students"> <view class="persons">{{index}} - {{item.name}}</view> </view>data: { students : [ {name : "张三", age : 18}, {name : "李四", age : 20} ] },</code> 条件渲染 <code class="line-numbers"><view v-if="show"> 这里是条件展示的内容....</view>show:false</code> hidden <code class="line-numbers"><view v-hidden="show"> 这里是条件展示的内容.... </view></code> class style 绑定 <code class="line-numbers"><view :class="{ active: isActive }">111</view><view class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }">222</view<view class="static" :class="[activeClass, errorClass]">333</view><view class="static" v-bind:class="[isActive ? activeClass : '', errorClass]">444</view><view class="static" v-bind:class="[{ active: isActive }, errorClass]">555</view><view v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">666</view><view v-bind:style="[{ color: activeColor, fontSize: fontSize + 'px' }]">777</view><template> <!-- 支持 --> <view class="container" :class="computedClassStr"></view> <view class="container" :class="{active: isActive}"></view> <!-- 不支持 --> <view class="container" :class="computedClassObject"></view></template></code> 事件处理、事件绑定、事件传参 web uniapp 对应表 click: 'tap', touchstart: 'touchstart', touchmove: 'touchmove', touchcancel: 'touchcancel', touchend: 'touchend', tap: 'tap', longtap: 'longtap', input: 'input', change: 'change', submit: 'submit', blur: 'blur', focus: 'focus', reset: 'reset', confirm: 'confirm', columnchange: 'columnchange', linechange: 'linechange', error: 'error', scrolltoupper: 'scrolltoupper', scrolltolower: 'scrolltolower', scroll: 'scroll' 在 input 和 textarea 中 change 事件会被转为 blur 事件。 事件绑定 @click <code class="line-numbers"><view class="demo" @click="clickTest" @longtap="longtap"></view>methods:{ clickTest: function(e){ console.log(e); console.log('click'); }, longtap: function(e){ console.log(e); console.log('longtap'); } }</code> 事件传参 <code class="line-numbers"><view> <view v-for="(item, index) in students" class="persons" @click="menuClick" v-bind:id="index">{{index}} - {{item.name}}</view> </view>menuClick : function(e){ console.log(e); console.log(e.target.id); }</code> 组件 基本组件 https://uniapp.dcloud.io/component/README 表单组件 http://uniapp.dcloud.io/component/button navigator http://www.hcoder.net/tutorials/info_1347.html <code class="line-numbers"> <navigator url="./test?title=navigate" hover-class="navigator-hover"> <button type="default">跳转到新页面</button> </navigator></code> 媒体组件 地图组件 <code class="line-numbers"> <map style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude" :markers="covers"> </map> markers: [{ width : 40, height: 40, latitude: 39.909, longitude: 116.39742, iconPath: '../../../static/p.png' }]</code> uni.request(OBJECT) 发起网络请求 get <code class="line-numbers"> uni.request({ url: 'https://demo.hcoder.net', success: function (res) { console.log(res.data); }</code> post <code class="line-numbers">uni.request({ url: 'https://demo.hcoder.net/index.php', data: {name : 'hcoder...', 'age' : 18}, method:"POST", header : {'content-type':'application/x-www-form-urlencoded'}, success: function (res) { console.log(res.data); }});</code> 图片的相关接口 http://www.hcoder.net/tutorials/info_1351.html <code class="line-numbers">uni.chooseImage(OBJECT) 从本地相册选择图片或使用相机拍照。 uni.chooseImage({ count: 6, //默认9 sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有 sourceType: ['album'], //从相册选择 success: function (res) { console.log(JSON.stringify(res.tempFilePaths)); } });预览图片 uni.chooseImage({ count: 6, sizeType: ['original', 'compressed'], sourceType: ['album'], success: function (res) { // 预览图片 uni.previewImage({ urls: res.tempFilePaths }); } });uni.getImageInfo(OBJECT) 获取图片信息 uni.chooseImage({ count: 1, sourceType: ['album'], success: function (res) { uni.getImageInfo({ src: res.tempFilePaths[0], success: function (image) { console.log(image.width); console.log(image.height); } }); } });uni.saveImageToPhotosAlbum(OBJECT)保存图片到系统相册 uni.saveImageToPhotosAlbum({ filePath: res.tempFilePaths[0], success: function () { console.log('save success'); } });</code> 上传 uni.uploadFile(OBJECT) 客户端发起一个 POST 请求,其中 content-type 为 multipart/form-data。 <code class="line-numbers"> <template> <view> <view> <progress :percent="percent" stroke-width="10"></progress> </view> <view> <button type="primary" :loading="loading" :disabled="disabled" @click="upload">选择照片</button> </view> </view> </template> <script> var _self; export default { data:{ percent:0, loading:false, disabled:false }, methods : { upload : function(){ _self = this; uni.chooseImage({ count: 1, sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有 sourceType: ['album'], //从相册选择 success: function (res) { const tempFilePaths = res.tempFilePaths; const uploadTask = uni.uploadFile({ url : 'https://demo.hcoder.net/index.php?c=uperTest', filePath: tempFilePaths[0], name: 'file', formData: { 'user': 'test' }, success: function (uploadFileRes) { console.log(uploadFileRes.data); } }); uploadTask.onProgressUpdate(function (res) { _self.percent = res.progress; console.log('上传进度' + res.progress); console.log('已经上传的数据长度' + res.totalBytesSent); console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend); }); }, error : function(e){ console.log(e); } }); } }, onLoad:function(){ } } </script> <?php class uperTestController extends witController{ public function index(){ if(!empty($_FILES['file'])){ //获取扩展名 $exename = $this->getExeName($_FILES['file']['name']); if($exename != 'png' && $exename != 'jpg' && $exename != 'gif'){ exit('不允许的扩展名'); } $imageSavePath = uniqid().'.'.$exename; if(move_uploaded_file($_FILES['file']['tmp_name'], $imageSavePath)){ echo $imageSavePath; } } } public function getExeName($fileName){ $pathinfo = pathinfo($fileName); return strtolower($pathinfo['extension']); } }</code> 数据缓存 uni.setStorage(OBJECT) 异步 uni.setStorageSync(KEY,DATA)同步 uni.getStorage(OBJECT)异步 uni.getStorageSync(KEY)同步 uni.getStorageInfo(OBJECT)异步 uni.getStorageInfoSync()同步 uni.removeStorage(OBJECT)异步 uni.removeStorageSync(KEY)同步 uni.clearStorage() uni.clearStorageSync()同步 设备相关 https://uniapp.dcloud.io/api/system/info 交互反馈 uni.showToast uni.showLoading uni.hideToast uni.hideLoading uni.showModal uni.showActionSheet http://uniapp.dcloud.io/api/system/info 设置导航条 uni.setNavigationBarTitle uni.showNavigationBarLoading uni.hideNavigationBarLoading uni.setNavigationBarColor http://uniapp.dcloud.io/api/ui/navigationbar 导航 uni.navigateTo uni.redirectTo uni.reLaunch uni.switchTab uni.navigateBack http://uniapp.dcloud.io/api/ui/navigate?id=navigateback 下拉树新 onPullDownRefresh 需要在 pages.json 里,找到的当前页面的pages节点,并在 style 选项中开启 enablePullDownRefresh 当处理完数据刷新后,uni.stopPullDownRefresh 可以停止当前页面的下拉刷新。 uni.startPullDownRefresh(OBJECT) 开始下拉刷新,调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。 <code class="line-numbers"> page.json 开启下拉刷新 { "pages": [ { "path": "pages/index/index", "style": { "navigationBarTitleText": "hi uni", "enablePullDownRefresh": true } }, ....... index.vue <template> <view> <view v-for="(item, index) in newsList" class="newslist">{{item}}</view> </view> </template> <script> var _self; export default { data:{ newsList:[] }, onLoad:function(){ _self = this; }, onPullDownRefresh:function(){ this.getnewsList(); }, methods:{ getnewsList : function(){ uni.showNavigationBarLoading(); uni.request({ url: 'https://demo.hcoder.net/index.php?user=hcoder&pwd=hcoder&m=list1&page=1', method: 'GET', success: function(res){ console.log(res); _self.newsList = res.data.split('--hcSplitor--'); uni.hideNavigationBarLoading(); uni.stopPullDownRefresh(); } }); } }, } </script> <style> .newslist{padding:10px; font-size:28px;} </style></code> 上拉加载更多 <code><template> <view> <view v-for="(item, index) in newsList" class="newslist">{{item}}</view> <view class="loading">{{loadingText}}</view> </view></template><script>var _self, page = 1, timer = null;export default { data:{ newsList:[], loadingText:'加载中...' }, onLoad:function(){ _self = this; this.getnewsList(); }, onPullDownRefresh:function(){ this.getnewsList(); }, onReachBottom:function(){ if(timer != null){ clearTimeout(timer); } timer = setTimeout(function(){ _self.getmorenews(); }, 1000); }, methods:{ getmorenews : function(){ if(_self.loadingText != '' && _self.loadingText != '加载更多'){ return false; } _self.loadingText = '加载中...'; uni.showNavigationBarLoading(); uni.request({ url: 'https://demo.hcoder.net/index.php?user=hcoder&pwd=hcoder&m=list1&page='+page, method: 'GET', success: function(res){ _self.loadingText = ''; if(res.data == null){ uni.hideNavigationBarLoading(); _self.loadingText = '已加载全部'; return false; } page++; console.log(res); _self.newsList = _self.newsList.concat(res.data.split('--hcSplitor--')); _self.loadingText = '加载更多'; uni.hideNavigationBarLoading(); } }); }, getnewsList : function(){ page = 1; uni.showNavigationBarLoading(); uni.request({ url: 'https://demo.hcoder.net/index.php?user=hcoder&pwd=hcoder&m=list1&page=1', method: 'GET', success: function(res){ page++; _self.newsList = res.data.split('--hcSplitor--'); uni.hideNavigationBarLoading(); uni.stopPullDownRefresh(); _self.loadingText = '加载更多'; } }); } }}</script><style>.newslist{padding:10px; line-height:60px; font-size:28px;}.loading{text-align:center; line-height:80px;}</style></code> 小程序登陆 http://www.hcoder.net/tutorials/info_1360.html h5+app登陆 http://www.hcoder.net/tutorials/info_1361.html 自定义组件 http://www.hcoder.net/tutorials/info_1362.html