如果你會使用Vue那咱們繼續吧!
uni-app 是一個使用 Vue.js 開發所有前端應用的框架,開發者編寫一套代碼,可發布到iOS、Android、H5、以及各種小程序(微信/支付寶/百度/頭條/QQ/釘釘)等多個平臺。
多端泛濫 iOS、Android、H5、以及各種小程序(微信/支付寶/百度/頭條/QQ/釘釘)多套平臺,多套文檔,加大開發維護成本
1、跨平臺
一套代碼多端發行,而不失優雅(條件編譯,保留不同平臺獨有特色功能方法調用)
<!--#ifdef MP-WEIXIN--> <view>只會編譯小程序</view><!--endif--><!--#ifdef XX-XXX--> <view>只會編譯XXX</view><!--endif-->
2、通用技術棧,學習成本低
Vue的語法,微信小程序Api,內嵌mpvue可以直接遷移,如果你會Vue可以直接入門
3、生態豐富
支持npm下載第三方模塊,支持小程序自定義組件,SDK,兼容mpvue組件,支持原生混合編碼
可以下載兩個進行配置 ,測試微信小程序與支付寶小程序同步實現
編譯工具下載HBuilderX
微信小程序開發IDE
支付寶小程序 IDE
推薦使用 HBuildX 進行開發
創建目錄
運行項目
一、找到創建項目uni裡面的項目目錄
二、找到 manifest.js文件輸入
1、裡面有所有平臺配置文件
需要不同平臺測試,需要分別配置不同平臺
2、選擇微信小程序配置
配置小程序AppID
點擊最上面工具欄選擇運行
選擇運行到小程序模擬器
選擇微信小程序開發工具
第一次配置小程序開發者工具,需要打開服務
三、打開微信小程序開發左上角小
安全設置,將服務埠開啟。||工具 -> 設置 -> 安全設置,將服務埠開啟。
四、選擇HBuild停止服務,重新運行自動打開編輯工具
.nvue 是對weex的增強。如果你不開發App,那麼你不太需要nvue。
發布測試
選擇HBuild最上面工具欄,點擊發布進行打包,根據命令行提示再點擊微信開發者工具發布
注意不要直接修改微信開發工具目錄,以HBuild開發目錄為主
目錄介紹
與小程序配置相似
pages //存放分頁目錄static //存放應用引用靜態資源main.js //入口文件mainfest.json //跨平臺所有配置項文件pages.json //全局配置文件,類似App.json uni.scss//全局scss文件,在分頁任何位置,注意 style lang="scss" 需要設置 scssApp.vue // 應用配置,用來配置App全局樣式以及監聽
統一參照uni-app官方文檔
添加分頁
pages.json文件 style 為分頁配置項,類似小程序 page.json
修改 pages.json
知識點: uni-app分頁配置在style裡面寫,globalStyle寫全部樣式配置,在一個配置文件,這裡是有區別原生小程序開發,具體參照uni-app文檔進行配置 pages.json
配置項
配置項
navigationBarBackgroundColor HexColor //#000000 導航欄背景顏色 navigationBarTextStyle String white //導航欄標題顏色,僅支持 black/white navigationBarTitleText String //導航欄標題文字內容 navigationStyle String default //導航欄樣式,僅支持 default/custom。 backgroundColor HexColor //#ffffff 下拉窗口的背景色 微信小程序
全局配置
globalStyle: { //...全局配置}
局部配置 參照 pages.style內容
> pages數組,決定誰排在前面
修改pages導致文件查找失敗,檢查無誤,重啟編輯工具
pages:[ { path: "xxx/xxx/xxx", style: { //...局部配置 } }]
系統自帶底部tabBar欄配置
如果配置tabBar需要保證abBar第一個路由,配置在第一個pages的第一個
"tabBar": { "color": "#7A7E83", "selectedColor": "#3cc51f", "borderStyle": "black", "backgroundColor": "#ffffff", "list": [{ "pagePath": "pages/component/index", "iconPath": "static/image/icon_component.png", "selectedIconPath": "static/image/icon_component_HL.png", "text": "組件" }, { "pagePath": "pages/API/index", "iconPath": "static/image/icon_API.png", "selectedIconPath": "static/image/icon_API_HL.png", "text": "接口" }] }
優先嘗試根據Vue使用操作,例如使用 v-for 替換wx:for
表達式
僅此而已,有Vue使用相似,不能使用流程控制語句
<view>{{name}}</view> <!--讀取變量--><view>{{msg+'Msea'}}</view><!--拼接變量--><view>{{10-9}}</view> <!--運算符--><view>{{0||"NB"}}</view> <!--邏輯運算符--><!--數據類型方法--><view>{{'Msea'.indexOf('xxx')!==-1?'太原最靚仔':'no'}}</view><view>{{"我愛北京天安門".substr(0,2)}}</view>
屬性綁定
<image :src="'https://www.w3school.com.cn/i/eg_tulip.jpg'"/>
動態樣式
<view :class="`${'box'}`+''+`12`">{{`1`+1}}</view> <view :class="{className:true}"></view><view :class="['box',true?'col2':'']"></view><view class="box1212" :class="['box',true?'col2':'']"></view><view :style="{ color: 'red', fontSize: 20 + 'px' }">666</view><view :style="[{ color: pink, fontSize: 20 + 'px' }]">777</view>
指令
<view class="box" v-show="true">v-show</view><view v-if="text==='登陸'">{{'歡迎'+name+'登陸'}}</view><view v-else-if="text==='未登陸'">未登陸</view><view v-else>!!!!!</view><input type="text" v-model="val">{{val}} <!--數據雙項綁定--><!--支持v-model修飾符--><input type="text" v-model.number="val">{{val+11}}
事件
<!--事件,阻止事件冒泡--><view @click="test1(true)"> <!--傳入參數--> <button @click.stop="test2">test</button></view>
遍歷
<!--數組遍歷--><ul id="example-1"> <li v-for="(item,index) in items"> {{ item.message }} </li></ul><!--對象遍歷--><div v-for="(value, name, index) in object"> {{ index }}. {{ name }}: {{ value }}</div>
頁面棧最多十層。使用uni.navigateTo頻繁切換,會導致棧溢出,跳轉失敗
// 非tabbar配置的頁面我們使用 navigateTo跳轉時保留老頁面,一般用於需要返回uni.navigateTo({ url: "../one/one?name=Msea"})// 跳轉pages.json>tabbar>配置過的頁面,使用 switchTabuni.switchTab({ url: "../one/one"})// 不保留當前頁面,跳轉非配置頁面uni.redirectTo({ url: "../one/one"})
響應式單位rpx
推薦使用最近公告推薦使用rpx替代upx
基於蘋果6 1px =2rpx
<view class="box1"></view><view class="box2"></view><style lang="scss">.box1{ width:200rpx; height:200rpx; background:red;}.box2{ width:100px; height:100px; background:pink;}</style>
微信小程序裡面沒有 window,document對象,那如果需要進行dom操作
var query=uni.createSelectorQuery();query.select(".titlerh").boundingClientRect((nodes)=>{ console.log(nodes)}).exec();query.select(".box1") .boundingClientRect() .selectAll(".box2") .boundingClientRect() .exec((res)=>{ console.log(res);});
創建文件夾 components目錄統一寫法,滑鼠右鍵創建組件
所有組件與屬性名都是小寫,單詞之間以連字符-連接。
<template> <uni-test/></template><script> import uniTest from "../../components/test.vue" export default { data() { return {}; }, methods:{ test(){ this.text = "登錄"; } }, components: { uniTest //引入組件 } }</script><style lang="scss"> ...style</style>
應用生命周期 App.vue
App({ onLaunch (options) { console.log("小程序初始化"); }, onShow (options) console.log("小程序顯示"); }, onHide () { console.log("小程序隱藏"); }})
分頁生命周期 pages
Page({ onLoad: function(options) { // 頁面創建時執行 console.log("頁面加載"); }, onShow: function() { console.log("頁面進入"); }, onReady: function() { console.log("頁面首次渲染完畢時執行"); }, onHide: function() { console.log("頁面離開"); }, onPullDownRefresh: function() { // 觸發下拉刷新時執行 console.log("下拉觸發"); //enablePullDownRefresh 開啟下拉 }, onReachBottom: function() { // 頁面觸底時執行 console.log("下拉到底"); }, onShareAppMessage: function (e) { // 頁面被用戶分享時執行 //通過按鈕調用 //點擊觸發彈窗 <button open-type="share">分享</button> console.log("用戶分享"); return { title: '妹子圖片', path: '/pages/index/index', //當前頁面 path imageUrl: "/images/1.jpg", desc: '面向百度開發', success: (res) => { console.log("轉發成功", res); }, fail: (res) => { console.log("轉發失敗", res); } } }, onPageScroll: function() { console.log("頁面滾動時執行"); }, onResize: function() { console.log("屏幕旋轉觸發"); }})
組件生命周期
uni-app components組件支持的生命周期,與vue標準組件的生命周期相同。wx小程序支持生命周期
beforeCreate(){} // 在實例初始化之後被調用created(){} // 在實例創建完成後被立即調用。beforeMount(){} // 在掛載開始之前被調用。mounted(){} // 掛載到實例上去之後調用。beforeDestroy(){} // 實例銷毀之前調用。在這一步,實例仍然完全可用。
使用方法與微信小程序一致,推薦使用uni-ui
<scroll-view :scroll-x="true" style="boder:1px solid red;white-space:nowrap" @scroll="scroll"> <view style=" background:red; width:200px;height:100px; display:inline-block;" ></view> <view style="background:yellow;width:200px;height:100px;display:inline-block;"></view> <view style="background:pink;width:200px;height:100px;display:inline-block;"></view> <view style="background:blue;width:200px;height:100px;display:inline-block;"></view></scroll-view>
引入三方UI
例如 Vant Weapp 下載
{ "path" : "pages/one/one", "style" : { "usingComponents":{ "van-button": "/wxcomponents/dist/button/index" //參照wx組件引 } }}
<style> /*每個頁面公共css */ @import "/wxcomponents/dist/common/index.wxss";</style>
獲取用戶授權彈窗
<button open-type="getUserInfo" @getuserinfo="eventName"> 獲取頭像暱稱 </button>getUserInfo: function(e) { app.globalData.userInfo = e.detail.userInfo this.setData({ userInfo: e.detail.userInfo, hasUserInfo: true })}
返回所有用戶授權
wx.getSetting({success:()=>{"返回用戶所有用戶授權"}})
照相機接口
因為,調用照相機獲取臨時圖片格式,直接上傳三方伺服器,是不支持的,需要微信做解析,轉發
wx.uploadFile 上傳微信需要做轉發看不到傳輸的參數
uni.chooseImage({ count: 1, //圖片張數 sizeType: ['original', 'compressed'],//原圖,壓縮圖, sourceType: ['album', 'camera'], //本地相冊,拍照 success :res=> { const tempFilePaths = res.tempFilePaths//微信小程序圖片臨時路徑 this.setData({tempFilePaths}); }})// 預覽接口viewImgs(index) { uni.previewImage({ current: this.data.tempFilePaths[index], // 當前顯示圖片的http連結 urls:this.data.tempFilePaths // 需要預覽的圖片http連結列表 });}, //小程序圖片上傳 fileUplaod() { uni.uploadFile({ url: "http://wxs.ixinangou.net/index/index/dofiles", filePath: this.data.tempFilePaths[0], name: "file", //上傳圖片key formData: { user: "MSea" //需要額外攜帶參數 }, header: { "content-type": "multipart/form-data" }, success: res => { console.log("data"); } }); }
請求
微信原生請求接口
注意設置,不校驗合法域名,回憶怎麼添加合法域名
//GET 會自動拼接參數//queryStringParamsuni.request({ method: "GET", url: "https://cnodejs.org/api/v1/topics", data: { uname: "Msea" }, success: (res) => { console.log(res) }})//POST 默認參數為payLoad,為jsonuni.request({ method: "POST", url: "https://cnodejs.org/api/v1/topics", data: { uname: "Msea" }, success: (res) => { console.log(res) }})//POST form-data 數據 // 'content-type': 'multipart/form-data' 用於文件上傳 uni.request({ url: 'https://cnodejs.org/api/v1/topic/5433d5e4e737cbe96dcef312', data:{fileId:'123'}, method:'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, success:function(res){}})
地圖組件
<map id="map" longitude="經度" latitude="緯度" scale="縮放級別(14)" bindcontroltap="點擊地圖觸發FN" markers="{{添加標記}}" bindtap="markertap" 點解地圖觸發 show-location 將地圖中心移置當前定位點,此時需設置地圖組件 show-location 為true。 style="width: 100%; height: 300px;"></map>
移動地圖中心點
移動端測試有效
onShow: function() { // 地圖上下文對象 this.mapCtx = uni.createMapContext('map'); }, ckMap(e){ //小程序不支持 Objcet.assign var temp={ iconPath: "/assets/img/local.png", id: 0, width: 25, height: 25, ...e.detail } var markers=this.data.markers; markers.push(temp); this.setData({markers},()=>{ var data={ ...e.detail }; this.mapCtx.moveToLocation(data) }) }
定位
uni.getLocation({ type: 'gcj02', //騰訊地圖坐標系 success:(res)=> { const latitude = res.latitude const longitude = res.longitude }})
用戶授權彈窗
app.json配置文件
//app.json{ "pages": ["pages/index/index"], "permission": { "scope.userLocation": { "desc": "熊貓創客需要獲取您的位置親" // 高速公路行駛持續後臺定位 } }}
獲取當前位置並移動地圖中心點
wx.getLocation({ type: 'gcj02', //騰訊地圖坐標系 success: (res) => { const latitude = res.latitude const longitude = res.longitude var temp = { iconPath: "/assets/img/local.png", id: 0, width: 25, height: 25, latitude, longitude } var markers = this.data.markers; markers.push(temp); this.setData({ markers }, () => { var data = { latitude, longitude }; this.mapCtx.moveToLocation(data) }) }})
uni-app已經內置了vuex
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({ state: { num:0 }, mutations: { add(store){ store.num++; } }, actions: {}})export default store
import store from './store'Vue.prototype.$store = store; const app = new Vue({ ...App, store})app.$mount()
<template> <view> <view>{{num}}</view> <button @click="test">test1</button> </view></template><script> import { mapState, mapMutations } from 'vuex'; export default { computed:{ ...mapState(['num']) }, methods:{ test() { console.log(this.$store.commit("add")) } } }</script>
可以安裝支付寶小程序進行測試
#ifdef %PLATFORM% //這些代碼只在該平臺編譯 #endif #ifdef : if defined 僅在某個平臺編譯#ifndef : if not defined 在除裡該平臺的其他編譯#endif : end if 結束條件編譯%PLATFORM% 需要編譯的平臺,上面的MP就是各個小程序的意思常用 %PLATFORM% h5 h5平臺MP-WEIXIN 微信小程序MP-ALIPAY 支付寶小程序MP-BAIDU 百度小城MP-TOUTIAO 頭條小程序
總結: 優先使用Vue用法,只要實現微信開發,支持wx,ui,api,統一使用uni的Api,多看文檔