好程式設計師web前端培訓分享之uni-app學習筆記uni-app詳解

好程式設計師發表於2020-05-11

    好程式設計師 web前端培訓分享之 uni-app學習筆記 uni-app詳解 uni-app (一套程式碼 ,多端發行 )如果你會使用 Vue那我們們繼續吧 !

什麼是uni-app?

uni-app 是一個使用  Vue.js  開發所有前端應用的框架,開發者編寫一套程式碼,可釋出到iOS、Android、H5、以及各種小程式等多個平臺。

誕生背景

多端氾濫 iOS、Android、H5、以及各種小程式多套平臺,多套文件,加大開發維護成本

uni-app特點

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 進行開發

跨多端小程式開發

建立目錄

00001.  開啟HBuilderX

00002.  左上角建立專案

00003.  選擇uni-app專案

00004.  下面是提供幾個Demo專案,可以建立學習

00005.  專案名稱能不能大寫,建立專案

執行專案

一、找到建立專案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 需要設定 scss App.vue   // 應用配置,用來配置App全域性樣式以及監聽

統一參照uni-app官方文件

初探uni-app

新增分頁

00001.  滑鼠移動pages右鍵

00002.  右鍵新建頁面,注意檢查pages.json檔案會自動寫入pages項,檔案路徑

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 = "' />

動態樣式

< 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>配置過的頁面,使用 switchTab uni.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 : 200 rpx;

     height : 200 rpx;

     background : red ;}. box2 {

     width : 100 px ;

     height : 100 px ;

     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(){}   // 例項銷燬之前呼叫。在這一步,例項仍然完全可用。

UI元件

uni-ui

使用方法與微信小程式一致,推薦使用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 

00001.  根目錄下建立 wxcomponents

00002.  將下載包內部 dist包貼上到uni-app根目錄wxcomponents資料夾下

00003.  配置

{

     "path"   :   "pages/one/one" ,

         "style"   :   {

             "usingComponents" :{

                 "van-button" :   "/wxcomponents/dist/button/index"   //參照wx元件引

             }

         }}

00001.  App.vue,引入樣式

< style >

/*每個頁面公共css */

@ import   "/wxcomponents/dist/common/index.wxss" ;</ style >

00001.  one分頁內直接使用van-button元件,不需要引入

00002.  注意如果報錯,檢查路徑如果沒有問題,可以選擇重編輯器重新啟動微信開發工具

常用API呼叫

獲取使用者授權彈窗

< 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 :   " ,

       filePath :   this .data.tempFilePaths[ 0 ],

       name :   "file" ,   //上傳圖片key        formData :   {

         user :   "MSea"   //需要額外攜帶引數        },

       header :   {

         "content-type" :   "multipart/form-data"

       },

       success :   res   =>   {

         console.log( "data" );

       }

     });

   }

請求

微信原生請求介面

注意設定,不效驗合法域名,回憶怎麼新增合法域名

//GET 會自動拼接引數//queryStringParams uni.request({

     method :   "GET" ,

     url :   " ,

     data :   {  

         uname :   "Msea"

     },

     success :   (res)   =>   {

         console.log(res)

     }}) //POST 預設引數為payLoad,為json uni.request({

     method :   "POST" ,

     url :   " ,

     data :   {  

         uname :   "Msea"  

     },

     success :   (res)   =>   {

         console.log(res)

     }}) //POST form-data 資料 // 'content-type': 'multipart/form-data'  用於檔案上傳   uni.request({

    url :   ' ,

     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)

         })

     }})

vuex

uni-app已經內建了vuex

00001.  在專案的根目錄下, 建立一個名為store的資料夾

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

00001.  main.js入口檔案引入

import   store   from   './store' Vue.prototype.$store   =   store;   

const   app   =   new   Vue({

     ...App,

store})app.$mount()

00001.  元件內引入

< 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,多看文件

 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69913864/viewspace-2691264/,如需轉載,請註明出處,否則將追究法律責任。

相關文章