日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【uni-app】uni-app的基础知识

發布時間:2023/12/8 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【uni-app】uni-app的基础知识 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

uni-app的基本使用

課程介紹:

基礎部分:

  • 環境搭建
  • 頁面外觀配置
  • 數據綁定
  • uni-app的生命周期
  • 組件的使用
  • uni-app中樣式學習
  • 在uni-app中使用字體圖標和開啟scss
  • 條件注釋跨端兼容
  • uni中的事件
  • 導航跳轉
  • 組件創建和通訊,及組件的生命周期
  • uni-app中使用uni-ui庫

項目:黑馬商城項目

1.uni-app介紹 官方網頁

uni-app 是一個使用 Vue.js 開發所有前端應用的框架,開發者編寫一套代碼,可發布到iOS、Android、H5、以及各種小程序(微信/支付寶/百度/頭條/QQ/釘釘)等多個平臺。

即使不跨端,uni-app同時也是更好的小程序開發框架。

具有vue和微信小程序的開發經驗,可快速上手uni-app

為什么要去學習uni-app?

相對開發者來說,減少了學習成本,因為只學會uni-app之后,即可開發出iOS、Android、H5、以及各種小程序的應用,不需要再去學習開發其他應用的框架,相對公司而言,也大大減少了開發成本。

1.1環境搭建

安裝編輯器HbuilderX 下載地址

HBuilderX是通用的前端開發工具,但為uni-app做了特別強化。

下載App開發版,可開箱即用

安裝微信開發者工具 下載地址

1.2利用HbuilderX初始化項目

  • 點擊HbuilderX菜單欄文件>項目>新建

  • 選擇uni-app,填寫項目名稱,項目創建的目錄

1.3運行項目

在菜單欄中點擊運行,運行到瀏覽器,選擇瀏覽器即可運行

項目運行-瀏覽器:

項目運行-微信開發者工具

注意事項:
(1)使用微信開發者工具運行項目時,需要添加微信開發者工具的目錄
(2)在微信開發者工具-設置-安全設置:打開端口

注意:

  • 如果是第一次使用,需要先配置小程序ide的相關路徑,才能運行成功
  • 微信開發者工具在設置中安全設置,服務端口開啟

1.4 介紹項目目錄和文件作用

  • pages.json 文件用來對 uni-app 進行全局配置,決定頁面文件的路徑、窗口樣式、原生的導航欄、底部的原生tabbar 等

  • manifest.json 文件是應用的配置文件,用于指定應用的名稱、圖標、權限等。

  • App.vue是我們的跟組件,所有頁面都是在App.vue下進行切換的,是頁面入口文件,可以調用應用的生命周期函數。

  • main.js是我們的項目入口文件,主要作用是初始化vue實例并使用需要的插件。

  • uni.scss文件的用途是為了方便整體控制應用的風格。比如按鈕顏色、邊框風格,uni.scss文件里預置了一批scss變量預置。

  • unpackage就是打包目錄,在這里有各個平臺的打包文件

  • pages所有的頁面存放目錄

  • static靜態資源目錄,例如圖片等

  • components組件存放目錄


為了實現多端兼容,綜合考慮編譯速度、運行性能等因素,uni-app 約定了如下開發規范:

  • 頁面文件遵循 Vue 單文件組件 (SFC) 規范
  • 組件標簽靠近小程序規范,詳見uni-app 組件規范
  • 接口能力(JS API)靠近微信小程序規范,但需將前綴 wx 替換為 uni,詳見uni-app接口規范
  • 數據綁定及事件處理同 Vue.js 規范,同時補充了App及頁面的生命周期
  • 為兼容多端運行,建議使用flex布局進行開發

2.全局配置和頁面配置

2.1通過globalStyle進行全局配置

用于設置應用的狀態欄、導航條、標題、窗口背景色等。詳細文檔

屬性類型默認值描述
navigationBarBackgroundColorHexColor#F7F7F7導航欄背景顏色(同狀態欄背景色)
navigationBarTextStyleStringwhite導航欄標題顏色及狀態欄前景顏色,僅支持 black/white
navigationBarTitleTextString導航欄標題文字內容
backgroundColorHexColor#ffffff窗口的背景色
backgroundTextStyleStringdark下拉 loading 的樣式,僅支持 dark / light
enablePullDownRefreshBooleanfalse是否開啟下拉刷新,詳見頁面生命周期。
onReachBottomDistanceNumber50頁面上拉觸底事件觸發時距頁面底部距離,單位只支持px,詳見頁面生命周期

2.2創建新的message頁面

右鍵pages新建message目錄,在message目錄下右鍵新建.vue文件,并選擇基本模板

<template><view>這是信息頁面</view> </template><script> </script><style> </style>

2.3通過pages來配置頁面

屬性類型默認值描述
pathString配置頁面路徑
styleObject配置頁面窗口表現,配置項參考 pageStyle

pages數組數組中第一項表示應用啟動頁

"pages": [ 、{"path":"pages/message/message"},{"path": "pages/index/index","style": {"navigationBarTitleText": "uni-app"}}]

通過style修改頁面的標題和導航欄背景色,并且設置h5下拉刷新的特有樣式

"pages": [ //pages數組中第一項表示應用啟動頁,參考:https://uniapp.dcloud.io/collocation/pages{"path":"pages/message/message","style": {"navigationBarBackgroundColor": "#007AFF","navigationBarTextStyle": "white","enablePullDownRefresh": true,"disableScroll": true,"h5": {"pullToRefresh": {"color": "#007AFF"}}}}]

2.4 配置tabbar

如果應用是一個多 tab 應用,可以通過 tabBar 配置項指定 tab 欄的表現,以及 tab 切換時顯示的對應頁。

Tips

  • 當設置 position 為 top 時,將不會顯示 icon,只會顯示文字
  • tabBar 中的 list 是一個數組,只能配置最少2個、最多5個 tab,tab 按數組的順序排序。

屬性說明:

屬性類型必填默認值描述平臺差異說明
colorHexColortab 上的文字默認顏色
selectedColorHexColortab 上的文字選中時的顏色
backgroundColorHexColortab 的背景色
borderStyleStringblacktabbar 上邊框的顏色,僅支持 black/whiteApp 2.3.4+ 支持其他顏色值
listArraytab 的列表,詳見 list 屬性說明,最少2個、最多5個 tab
positionStringbottom可選值 bottom、toptop 值僅微信小程序支持

其中 list 接收一個數組,數組中的每個項都是一個對象,其屬性值如下:

屬性類型必填說明
pagePathString頁面路徑,必須在 pages 中先定義
textStringtab 上按鈕文字,在 5+APP 和 H5 平臺為非必填。例如中間可放一個沒有文字的+號圖標
iconPathString圖片路徑,icon 大小限制為40kb,建議尺寸為 81px * 81px,當 postion 為 top 時,此參數無效,不支持網絡圖片,不支持字體圖標
selectedIconPathString選中時的圖片路徑,icon 大小限制為40kb,建議尺寸為 81px * 81px ,當 postion 為 top 時,此參數無效

案例代碼:

{"pages": [ //pages數組中第一項表示應用啟動頁,參考:https://uniapp.dcloud.io/collocation/pages{"path": "pages/message/message","style": {"navigationBarTitleText": "信息頁","navigationBarBackgroundColor": "red","h5":{"pullToRefresh":{"color":"blue"}}}},{"path": "pages/index/index","style": {"navigationBarTitleText": "my-first project"}},{"path": "pages/contact/contact","style": {"navigationBarTitleText": "信息頁","navigationBarBackgroundColor": "red","h5":{"pullToRefresh":{"color":"blue"}}}}],"globalStyle": {//導航欄標題顏色及狀態欄前景顏色,僅支持black/white"navigationBarTextStyle": "white","navigationBarTitleText": "my-first project",//導航欄背景顏色(同狀態欄背景色)"navigationBarBackgroundColor": "pink","backgroundColor": "#F8F8F8",//開啟下拉刷新"enablePullDownRefresh":true},"tabBar":{"color":"#F0AD4E","selectedColor":"#4CD964","backgroundColor":"#DD524D","borderStyle":"F8F8F8","list":[{"text":"首頁","pagePath":"pages/index/index","iconPath":"static/tab/home.png","selectedIconPath":"static/tab/home-active.png"},{"text":"信息","pagePath":"pages/message/message","iconPath":"static/tab/message.png","selectedIconPath":"static/tab/message-active.png"},{"text":"聯系我們","pagePath":"pages/contact/contact","iconPath":"static/tab/contact.png","selectedIconPath":"static/tab/contact-active.png"}]} }

2.5 condition啟動模式配置

啟動模式配置,僅開發期間生效,用于模擬直達頁面的場景,如:小程序轉發后,用戶點擊所打開的頁面。

屬性說明:

屬性類型是否必填描述
currentNumber當前激活的模式,list節點的索引值
listArray啟動模式列表

list說明:

屬性類型是否必填描述
nameString啟動模式名稱
pathString啟動頁面路徑
queryString啟動參數,可在頁面的 onLoad 函數里獲得
//啟動模式配置,僅開發期間有效,用于模擬直達頁面的場景。"condition":{"current":0,//當前激活的模式"list":{"name":"詳情頁",//模式名稱"path":"pages/detail/detail.vue",//啟動頁面"query":"interval=4000&autoplay=false"//啟動參數,前一個頁面傳遞過來的參數}}

3.組件的基本使用

uni-app提供了豐富的基礎組件給開發者,開發者可以像搭積木一樣,組合各種組件拼接稱自己的應用

uni-app中的組件,就像 HTML 中的 div 、p、span 等標簽的作用一樣,用于搭建頁面的基礎結構

3.1 text文本組件的用法(類似于span標簽)

001 - text 組件的屬性

屬性類型默認值必填說明
selectablebooleanfalse文本是否可選
spacestring.顯示連續空格,可選參數:ensp、emsp、nbsp
decodebooleanfalse是否解碼
  • text 組件相當于行內標簽、在同一行顯示
  • 除了文本節點以外的其他節點都無法長按選中
text的屬性:(1)selectable:文本是否可選(2)space:顯示連續空格ensp:中文字符空格一半大小emsp:中文字符空格大小nbsp:根據字體設置的空格大小(3)decode:是否解碼,目前都已經自動解碼了。可以解析的有 &nbsp; &lt; &gt; &amp; &apos; &ensp;

002 - 代碼案例

<template><view><view>信息</view><!-- text的屬性:(1)selectable:文本是否可選(2)space:顯示連續空格ensp:中文字符空格一半大小emsp:中文字符空格大小nbsp:根據字體設置的空格大小(3)decode:是否解碼,目前都已經自動解碼了。可以解析的有 &nbsp; &lt; &gt; &amp; &apos; &ensp; --><view> <!-- 等于span標簽,默認是不可以選中的--> <text>跳舞唱歌化妝</text> </view><view><!-- selectable文本是否可選,默認是不可以選的。 --><text selectable>跳舞唱歌化妝</text></view><!-- space顯示連續的空格ensp:中文字符空格一半大小emsp:中文字符空格大小nbsp:根據字體設置的空格大小 --><view><text space="ensp">跳舞 唱歌化妝</text></view><view><text space="emsp">跳舞 唱歌化妝</text></view><view><text space="nbsp">跳舞 唱歌化妝</text></view><view><text space="nbsp" decode>跳舞 唱歌化妝&amp;</text></view></view></template><script> </script><style> </style>

3.2 view視圖容器組件的用法(類似于div標簽)—template中必須有一個根組件

View 視圖容器, 類似于 HTML 中的 div

001 - 組件的屬性

002 - 代碼案例

<!-- view的屬性:hover-class:按下去時的樣式類hover-stop-propagation:阻止冒泡(在孩子處阻止冒泡)hover-start-time:按住后多久出現點擊態,單位毫秒hover-stay-time:手指松開后保留態的時間,單位毫秒 --><view class="box2" hover-class="box2-active"><view class="box1" hover-class="box1-active" hover-stop-propagation hover-start-time="2000" hover-stay-time="2000">我是一個大盒子</view></view>

3.3 button按鈕組件的用法

001 - 組件的屬性

屬性名類型默認值說明
sizeStringdefault按鈕的大小
typeStringdefault按鈕的樣式類型
plainBooleanfalse按鈕是否鏤空,背景色透明
disabledBooleanfalse是否按鈕
loadingBooleanfalse名稱是否帶 loading t圖標
  • button 組件默認獨占一行,設置 size 為 mini 時可以在一行顯示多個

002 - 案例代碼

<!-- button的屬性:size:設置大小type:按鈕樣式plain:鏤空disabled:禁止點擊loading:加載樣式 --><view><button>點擊</button><button size="default">點擊</button><button size="mini">點擊</button><button type="default">點擊</button><button type="primary">點擊</button><button type="warn">點擊</button><button type="primary" plain>點擊</button><button type="primary" disabled="false">點擊</button><button type="primary" loading>點擊</button></view>

3.4 image組件的使用

image

image的屬性:<view><image src="../../static/logo.png"></image><image src="../../static/logo.png" mode="aspectFit"></image><image src="../../static/logo.png" mode="aspectFill"></image> </view>

Tips

  • <image> 組件默認寬度 300px、高度 225px;
  • src 僅支持相對路徑、絕對路徑,支持 base64 碼;
  • 頁面結構復雜,css樣式太多的情況,使用 image 可能導致樣式生效較慢,出現 “閃一下” 的情況,此時設置 image{will-change: transform} ,可優化此問題。

4.uni-app中的樣式

  • rpx 即響應式px,一種根據屏幕寬度自適應的動態單位。以750寬的屏幕為基準,750rpx恰好為屏幕寬度。屏幕變寬,rpx 實際顯示效果會等比放大。

  • 使用@import語句可以導入外聯樣式表,@import后跟需要導入的外聯樣式表的相對路徑,用;表示語句結束

  • 支持基本常用的選擇器class、id、element等

  • 在 uni-app 中不能使用 * 選擇器。

  • page 相當于 body 節點

  • 定義在 App.vue 中的樣式為全局樣式,作用于每一個頁面。在 pages 目錄下 的 vue 文件中定義的樣式為局部樣式,只作用在對應的頁面,并會覆蓋 App.vue 中相同的選擇器。

  • uni-app 支持使用字體圖標,使用方式與普通 web 項目相同,需要注意以下幾點:

    • 字體文件小于 40kb,uni-app 會自動將其轉化為 base64 格式;

    • 字體文件大于等于 40kb, 需開發者自己轉換,否則使用將不生效;

    • 字體文件的引用路徑推薦使用以 ~@ 開頭的絕對路徑。

      @font-face {font-family: test1-icon;src: url('~@/static/iconfont.ttf');}
  • 如何使用scss或者less

5.uni-app中的數據綁定

在頁面中需要定義數據,和我們之前的vue一摸一樣,直接在data中定義數據即可

export default {data () {return {msg: 'hello-uni'}} }

5.1插值表達式的使用

  • 利用插值表達式渲染基本數據

    <view>{{msg}}</view>
  • 在插值表達式中使用三元運算

    <view>{{ flag ? '我是真的':'我是假的' }}</view>
  • 基本運算

    <view>{{1+1}}</view>

代碼:

<template><view><view>數據綁定的學習</view><view>{{msg}}</view><view>{{'你好'+'世界'}}</view><view>{{1+1}}</view><view>{{flag?'我是真的':'我是假的'}}</view></view> </template><script>export default{data(){return {msg:'hello world',flag:false}}} </script><style> </style>

5.2v-bind動態綁定屬性

在data中定義了一張圖片,我們希望把這張圖片渲染到頁面上

export default {data () {return {img: 'http://destiny001.gitee.io/image/monkey_02.jpg'}} }

利用v-bind進行渲染

<image v-bind:src="img"></image>

還可以縮寫成:

<image :src="img"></image>

5.3v-for的使用

data中定以一個數組,最終將數組渲染到頁面上

data () {return {arr: [{ name: '劉能', age: 29 },{ name: '趙四', age: 39 },{ name: '宋小寶', age: 49 },{ name: '小沈陽', age: 59 }]} }

利用v-for進行循環

<view v-for="(item,i) in arr" :key="i">名字:{{item.name}}---年齡:{{item.age}}</view>

5.4 代碼

<template><view><view>數據綁定的學習</view><view>{{msg}}</view><view>{{'你好'+'世界'}}</view><view>{{1+1}}</view><view>{{flag?'我是真的':'我是假的'}}</view><view><image :src="imgUrl"></image><image v-bind:src="imgUrl"></image></view><view v-for="(item,index) in list">序號:{{index}},名字:{{item.name}},年齡:{{item.age}}</view></view> </template><script>export default{data(){return {msg:'hello world',flag:false,imgUrl:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp05%2F191001214Q53137-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651155579&t=0b7de5e11caa724eaa217169648d7a4b",list:[{'name':'李四','age':'23'},{'name':'李四','age':'23'},{'name':'李四','age':'23'}]}}} </script><style> </style>

6. uni中的事件

6.1事件綁定

在uni中事件綁定和vue中是一樣的,通過v-on進行事件的綁定,也可以簡寫為@

<button @click="tapHandle">點我啊</button>

事件函數定義在methods中

methods: {tapHandle () {console.log('真的點我了')} }

6.2 事件傳參

  • 默認如果沒有傳遞參數,事件函數第一個形參為事件對象

    // template <button @click="tapHandle">點我啊</button> // script methods: {tapHandle (e) {console.log(e)} } // template <button @click="tapHandle($event)">點我啊</button> // script methods: {tapHandle (e) {console.log(e)} }
  • 如果給事件函數傳遞參數了,則對應的事件函數形參接收的則是傳遞過來的數據

    // template <button @click="tapHandle(1)">點我啊</button> // script methods: {tapHandle (num) {console.log(num)} }
  • 如果獲取事件對象也想傳遞參數

    // template <button @click="tapHandle(1,$event)">點我啊</button> // script methods: {tapHandle (num,e) {console.log(num,e)} }

7.uni的生命周期

7.1應用的生命周期(只能在App.vue里監聽應用的生命周期)

生命周期的概念:一個對象從創建、運行、銷毀的整個過程被成為生命周期。

生命周期函數:在生命周期中每個階段會伴隨著每一個函數的觸發,這些函數被稱為生命周期函數

uni-app 支持如下應用生命周期函數:

函數名說明
onLaunch當uni-app 初始化完成時觸發(全局只觸發一次)
onShow當 uni-app 啟動,或從后臺進入前臺顯示,通俗的說就是打開應用時,就會顯示
onHide當 uni-app 從前臺進入后臺,就是將該應用置于后臺
onError當 uni-app 報錯時觸發

App.vue的代碼

<script>// 應用的生命周期:[只能寫在App.vue中]// onLaunch:初始化完成時觸發,全局只觸發一次// onShow:啟動時,或者從后臺進入前臺顯示.通俗的說就是打開應用時,就會顯示// onHide:從前臺進入后臺,就是將該應用置于后臺// onError:報錯時觸發export default{onLaunch:function(){console.log("應用的生命周期:初始化時完成觸發,全局只觸發一次")},onShow:function(){console.log("應用的生命周期,啟動時或者從后臺進入前臺顯示,通俗的說就是打開應用時,就會顯示")},onHide:function(){console.log("應用的生命周期:從前臺進入后臺,就是將該應用置于后臺")},onError:function(){console.log("報錯了。")}} </script><style>/*每個頁面公共css */ </style>

7.2頁面的生命周期(寫在需要監聽的頁面上)

uni-app 支持如下頁面生命周期函數:

函數名說明平臺差異說明最低版本
onLoad(不會多次觸發監聽頁面加載,其參數為上個頁面傳遞的數據,參數類型為Object(用于頁面傳參),參考示例
onShow監聽頁面顯示。頁面每次出現在屏幕上都觸發,包括從下級頁面點返回露出當前頁面
onReady(不會觸發多次)監聽頁面初次渲染完成。
onHide監聽頁面隱藏
onUnload監聽頁面卸載

監聽index.vue為例:
index.vue的代碼:

<template><view class="content"><image class="logo" src="/static/logo.png"></image><view class="text-area"><text class="title">{{title}}</text></view></view> </template><script>export default {data() {return {title: 'Hello'}},onLoad() {console.log("onLoad,監聽頁面加載,不會多次")},onShow(){console.log("onShow,監聽頁面顯示,頁面每次出現在屏幕上時都觸發")},onReady(){console.log("onReady,監聽頁面初次渲染完成。")},onHide(){console.log("監聽頁面隱藏")},methods: {}} </script><style>.content {display: flex;flex-direction: column;align-items: center;justify-content: center;}.logo {height: 200rpx;width: 200rpx;margin-top: 200rpx;margin-left: auto;margin-right: auto;margin-bottom: 50rpx;}.text-area {display: flex;justify-content: center;}.title {font-size: 36rpx;color: #8f8f94;} </style>

7.3 組件的生命周期(與vue組件的一樣)

組件的生命周期

8.下拉刷新

8.1 開啟下拉刷新

在uni-app中有兩種方式開啟下拉刷新

  • 需要在 pages.json 里,找到的當前頁面的pages節點,并在 style 選項中開啟 enablePullDownRefresh【不建議全局開啟刷新】
  • 通過調用uni.startPullDownRefresh方法來開啟下拉刷新

8.1.1 方法1:通過配置文件開啟【不建議全局設置刷新】

創建list頁面進行演示

<template><view>杭州學科<view v-for="(item,index) in arr" :key="index">{{item}}</view></view> </template><script>export default {data () {return {arr: ['前端','java','ui','大數據']}}} </script><style> </style>

通過pages.json文件中找到當前頁面的pages節點,并在 style 選項中開啟 enablePullDownRefresh

{"path":"pages/list/list","style":{"enablePullDownRefresh": true} }

8.1.2 方法2: 通過API開啟

api文檔

uni.startPullDownRefresh()

8.2 監聽下拉刷新(與onLoad同級)

通過onPullDownRefresh可以監聽到下拉刷新的動作

export default {data () {return {arr: ['前端','java','ui','大數據']}},methods: {startPull () {uni.startPullDownRefresh()}},onPullDownRefresh () {console.log('觸發下拉刷新了')} }

8.3 關閉下拉刷新

uni.stopPullDownRefresh()

停止當前頁面下拉刷新。

案例演示

<template><view><button type="primary" @click="startPull">開啟下拉刷新</button>杭州學科<view v-for="(item,index) in arr" :key="index">{{item}}</view></view> </template> <script>export default {data () {return {arr: ['前端','java','ui','大數據']}},methods: {startPull () {uni.startPullDownRefresh()}},onPullDownRefresh () {this.arr = []setTimeout(()=> {this.arr = ['前端','java','ui','大數據']uni.stopPullDownRefresh()}, 1000);}} </script>

8.4完整代碼:

方法1:配置文件設置刷新

使用配置文件里的enablePullDownRefresh:true開啟刷新,使用onPullDownRefresh()進行刷新監聽,在監聽里面進行調用uni.stopPullDownRefresh()關閉刷新。
pages.json

{"pages": {"path": "pages/list/list","style": {"navigationBarTitleText": "my-first project",//開啟下拉刷新"enablePullDownRefresh":true}} }

list.vue

<template><view><view v-for="item in arr">{{item}}</view></view> </template><script>export default{data(){return {arr:['前端','java','ui','大數據']}},onPullDownRefresh(){setTimeout(()=>{console.log("下拉刷新了")this.arr=['前端','ui','java','大數據']uni.stopPullDownRefresh()},2000)}} </script><style> </style>

方法2:手動調用api開啟刷新

點擊按鈕進行手動調用uni.startPullDownRefresh(),開啟刷新。使用onPullDownRefresh監聽下拉加載事件,在監聽下拉加載事件里添加關閉加載的事件uni.stopPullDownRefresh()
代碼:

<template><view><view v-for="item in arr">{{item}}</view><button type="primary" @click="pullRefresh">點擊</button></view> </template><script>export default{data(){return {arr:['前端','java','ui','大數據']}},onPullDownRefresh(){setTimeout(()=>{console.log("下拉刷新了")this.arr=['前端','ui','java','大數據']uni.stopPullDownRefresh()},2000)},methods:{pullRefresh(){console.log("開啟手動刷新")uni.startPullDownRefresh()}}} </script><style> </style>

9. 上拉加載

通過在pages.json文件中找到當前頁面的pages節點下style中配置onReachBottomDistance可以設置距離底部開啟加載的距離,默認為50px

通過onReachBottom監聽到觸底的行為

<template><view><view v-for="item in arr">{{item}}</view><button type="primary" @click="pullRefresh">點擊</button></view> </template><script>export default{data(){return {arr:['前端','java','ui','大數據']}},onPullDownRefresh(){setTimeout(()=>{console.log("下拉刷新了")this.arr=['前端','ui','java','大數據']uni.stopPullDownRefresh()},2000)},onReachBottom(){console.log("頁面上拉觸底了~")},methods:{pullRefresh(){console.log("開啟手動刷新")uni.startPullDownRefresh()}}} </script><style>view{height: 600px;line-height: 100px;} </style> "pages": [ {"path": "pages/list/list","style": {"navigationBarTitleText": "my-first project",//開啟下拉刷新"enablePullDownRefresh":true,"onReachBottomDistance":950}},

10. 網絡請求

在uni中可以調用uni.request方法進行請求網絡請求

需要注意的是:在小程序中網絡相關的 API 在使用前需要配置域名白名單。

發送get請求

<template><view><button @click="sendGet">發送請求</button></view> </template> <script>export default {methods: {sendGet () {uni.request({url: 'http://localhost:8082/api/getlunbo',success(res) {console.log(res)}})}}} </script>

發送post請求

11. 數據緩存

11.1 uni.setStorage

官方文檔

將數據存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個異步接口。

代碼演示

<template><view><button type="primary" @click="setStor">存儲數據</button></view> </template><script>export default {methods: {setStor () {uni.setStorage({key: 'id',data: 100,success () {console.log('存儲成功')}})}}} </script><style> </style>

11.2 uni.setStorageSync

將 data 存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個同步接口。

代碼演示

<template><view><button type="primary" @click="setStor">存儲數據</button></view> </template><script>export default {methods: {setStor () {uni.setStorageSync('id',100)}}} </script><style> </style>

11.3 uni.getStorage

從本地緩存中異步獲取指定 key 對應的內容。

代碼演示

<template><view><button type="primary" @click="getStorage">獲取數據</button></view> </template> <script>export default {data () {return {id: ''}},methods: {getStorage () {uni.getStorage({key: 'id',success: res=>{this.id = res.data}})}}} </script>

11.4 uni.getStorageSync

從本地緩存中同步獲取指定 key 對應的內容。

代碼演示

<template><view><button type="primary" @click="getStorage">獲取數據</button></view> </template> <script>export default {methods: {getStorage () {const id = uni.getStorageSync('id')console.log(id)}}} </script>

11.5 uni.removeStorage

從本地緩存中異步移除指定 key。

代碼演示

<template><view><button type="primary" @click="removeStorage">刪除數據</button></view> </template> <script>export default {methods: {removeStorage () {uni.removeStorage({key: 'id',success: function () {console.log('刪除成功')}})}}} </script>

11.6 uni.removeStorageSync

從本地緩存中同步移除指定 key。

代碼演示

<template><view><button type="primary" @click="removeStorage">刪除數據</button></view> </template> <script>export default {methods: {removeStorage () {uni.removeStorageSync('id')}}} </script>

12. 上傳圖片、預覽圖片

12.1上傳圖片

uni.chooseImage方法從本地相冊選擇圖片或使用相機拍照。

案例代碼

<template><view><button @click="chooseImg" type="primary">上傳圖片</button><view><image v-for="item in imgArr" :src="item" :key="index"></image></view></view> </template><script>export default {data () {return {imgArr: []}},methods: {chooseImg () {uni.chooseImage({count: 9,//必須要寫成箭頭函數,要不然this就是window,無法獲取外面的數據success: res=>{this.imgArr = res.tempFilePaths}})}}} </script>

12.2 預覽圖片

結構

<view><image v-for="item in imgArr" :src="item" @click="previewImg(item)" :key="item"></image> </view>

預覽圖片的方法

previewImg (current) {uni.previewImage({urls: this.imgArr,current}) }

12.3 完整代碼

<template><view><view>詳情頁</view><view><button type="primary" @click="chooseImage">上傳圖片</button></view><view v-for="item in imgArr"><image :src="item" mode="" @click="previewImage(item)"></image></view></view></template><script>export default{data(){return{imgArr:[],}},methods:{chooseImage(){uni.chooseImage({count:5,success:res=>{console.log(res.tempFilePaths)this.imgArr=res.tempFilePaths},fail(res){console.log(res)}})},previewImage(current){uni.previewImage({current:current,urls:this.imgArr,longPressActions:{itemList:['收藏','保存','分享'],success(res){console.log("用戶選中了第",+(res.tapIndex+1)+"個按鈕,第"+(res.index+1)+"個圖片")}},success(){console.log("預覽成功")},fail(){console.log("預覽失敗")}})}}} </script><style> </style>

13. 條件注釋實現跨段兼容

條件編譯是用特殊的注釋作為標記,在編譯時根據這些特殊的注釋,將注釋里面的代碼編譯到不同平臺。

**寫法:**以 #ifdef 加平臺標識 開頭,以 #endif 結尾。

平臺標識

值平臺參考文檔
APP-PLUS5+AppHTML5+ 規范
H5H5
MP-WEIXIN微信小程序微信小程序
MP-ALIPAY支付寶小程序支付寶小程序
MP-BAIDU百度小程序百度小程序
MP-TOUTIAO頭條小程序頭條小程序
MP-QQQQ小程序(目前僅cli版支持)
MP微信小程序/支付寶小程序/百度小程序/頭條小程序/QQ小程序

13.1組件的條件注釋

代碼演示

<!-- #ifdef H5 --> <view>h5頁面會顯示 </view> <!-- #endif --> <!-- #ifdef MP-WEIXIN --> <view>微信小程序會顯示 </view> <!-- #endif --> <!-- #ifdef APP-PLUS --> <view>app會顯示 </view> <!-- #endif -->

13.2api的條件注釋

代碼演示

onLoad () {//#ifdef MP-WEIXINconsole.log('微信小程序')//#endif//#ifdef H5console.log('h5頁面')//#endif }

13.3樣式的條件注釋

代碼演示

/* #ifdef H5 */ view{height: 100px;line-height: 100px;background: red; } /* #endif */ /* #ifdef MP-WEIXIN */ view{height: 100px;line-height: 100px;background: green; } /* #endif */

14. uni中的導航跳轉

14.1利用navigator進行跳轉

navigator詳細文檔:文檔地址

(1)open-type="navigate" 跳轉到普通頁面(默認跳轉到單頁面上,保留當前頁面,打開新的頁面后,還可以返回到上一級頁面)

<navigator url="/pages/about/about" hover-class="navigator-hover"><button type="default">跳轉到關于頁面</button> </navigator>

(2)open-type="switchTab" 跳轉到tabbar頁面(如果不加open-type=“switchTab”,就跳轉不過來,卸載非tabbar頁面,打開新的頁面)卸載所有非tabbar頁面

<navigator url="/pages/message/message" open-type="switchTab"><button type="default">跳轉到message頁面</button> </navigator>

(3)open-type="redirect" 跳轉到單個頁面(卸載當前頁面,打開新的頁面,不可以返回到上一級頁面)卸載當前頁面

<navigator url="/pages/message/message" open-type="redirect"><button type="default">跳轉到message頁面</button> </navigator>

14.2利用編程式導航進行跳轉

導航跳轉文檔

(1)利用navigateTo進行導航跳轉

保留當前頁面,跳轉到應用內的某個頁面,使用uni.navigateBack可以返回到原頁面。

<button type="primary" @click="goAbout">跳轉到關于頁面</button>

通過navigateTo方法進行跳轉到普通頁面

goAbout () {uni.navigateTo({url: '/pages/about/about',}) }

(2)通過switchTab跳轉到tabbar頁面

跳轉到tabbar頁面

<button type="primary" @click="goMessage">跳轉到message頁面</button>

通過switchTab方法進行跳轉

goMessage () {uni.switchTab({url: '/pages/message/message'}) }

(3)redirectTo進行跳轉

關閉當前頁面,跳轉到應用內的某個頁面。

<!-- template --> <button type="primary" @click="goMessage">跳轉到message頁面</button> <!-- js --> goMessage () {uni.redirectTo({url: '/pages/message/message'}) }

通過onUnload測試當前組件確實卸載

onUnload () {console.log('組件卸載了') }

14.3導航跳轉傳遞參數

在導航進行跳轉到下一個頁面的同時,可以給下一個頁面傳遞相應的參數,接收參數的頁面可以通過onLoad生命周期進行接收

傳遞參數的頁面

goAbout () {uni.navigateTo({url: '/pages/about/about?id=80&name='小王'',}); }

接收參數的頁面

<script>export default {onLoad (options) {console.log(options)}} </script>

14.4 完整代碼

navigator.vue

<template><view><view>導航欄跳轉的學習</view><!-- 方法1:使用navigator組件。url:跳轉的地址open-type:跳轉的方式:默認是跳轉單頁面,不跳轉tab導航頁,如果要的話,改成switchTab。不卸載當前頁面,打開新的頁面,可以返回之前的頁面。navigate:默認跳轉單頁面(即沒有tab導航頁)redirect:卸載當前頁面,打開新的頁面,意思就是無法返回到之前的頁面。 --><navigator url="../datail/detail?id=20&name='小王'">跳轉詳情頁</navigator><navigator url="../message/message" open-type="switchTab">跳轉信息頁</navigator><navigator url="../datail/detail" open-type="redirect">跳轉詳情頁(卸載之前的頁面)</navigator><!-- 方法2:使用api跳轉的方式 --><button type="primary" @click="goDetail">跳轉到詳情頁(保留當前頁面,跳轉到應用的某個頁面,tarbar跳轉不過去)</button><button type="primary" @click="goMessage">跳轉到信息頁</button><button type="primary" @click="redirectDetail">跳轉到詳情頁(卸載當前頁面,跳轉到新的頁面)</button></view> </template><script>export default{data(){return{}},methods:{goDetail(){//保留當前頁面,跳轉到應用的某個頁面(tarbar跳轉不過去)uni.navigateTo({url:"../datail/detail"})},goMessage(){//卸載所有非tabbar的頁面,打開新的頁面uni.switchTab({url:"../message/message"})},redirectDetail(){//卸載當前頁面,打開新的頁面。uni.redirectTo({url:"../datail/detail"})}},onUnload(){console.log("當前頁面卸載了")}} </script><style> </style>

detail.vue

onLoad(options){// #ifdef H5console.log("h5頁面會顯示")console.log(options)// #endif// #ifdef MP-WEIXINconsole.log("微信小程序會顯示")// #endif},

15. uni-app中組件的創建

在uni-app中,可以通過創建一個后綴名為vue的文件,即創建一個組件成功,其他組件可以將該組件通過impot的方式導入,在通過components進行注冊即可

  • 創建login組件,在component中創建login目錄,然后新建login.vue文件

    <template><view>這是一個自定義組件</view> </template><script> </script><style> </style>
  • 在其他組件中導入該組件并注冊

    import login from "@/components/test/test.vue"
  • 注冊組件

    components: {test}
  • 使用組件

    <test></test>

15.1 組件的生命周期函數

beforeCreate在實例初始化之后被調用。詳見
created在實例創建完成后被立即調用。詳見用于初始化數據
beforeMount在掛載開始之前被調用。詳見
mounted掛載到實例上去之后調用。詳見 注意:此處并不能確定子組件被全部掛載,如果需要子組件完全掛載之后在執行操作可以使用$nextTickVue官方文檔用于操作dom
beforeUpdate數據更新時調用,發生在虛擬 DOM 打補丁之前。詳見僅H5平臺支持
updated由于數據更改導致的虛擬 DOM 重新渲染和打補丁,在這之后會調用該鉤子。詳見僅H5平臺支持
beforeDestroy實例銷毀之前調用。在這一步,實例仍然完全可用。詳見
destroyedVue 實例銷毀后調用。調用后,Vue 實例指示的所有東西都會解綁定,所有的事件監聽器會被移除,所有的子實例也會被銷毀。詳見可以銷毀的時候刪除定時器

15.2 代碼

uniapp的頁面index.vue

<template><view class="content"><!-- <image class="logo" src="/static/logo.png"></image><view class="text-area"><text class="title">{{title}}</text></view> --><test v-if="flag"></test><button @click="changeFlag">切換</button></view> </template><script>import test from '../components/test.vue'export default {data() {return {title: 'Hello',flag:true}},components:{test},methods: {changeFlag(){this.flag=!this.flag}}} </script><style>.content {display: flex;flex-direction: column;align-items: center;justify-content: center;}.logo {height: 200rpx;width: 200rpx;margin-top: 200rpx;margin-left: auto;margin-right: auto;margin-bottom: 50rpx;}.text-area {display: flex;justify-content: center;}.title {font-size: 36rpx;color: #8f8f94;} </style>

組件test.vue

<template><view>test</view></template><script>export default{data(){return {title:'hello',interId:'null',}},beforeCreate() {//開始初始化,但是還未加載監聽攔截,data中的數據還不能加載出來。console.log("beforeCreate:")console.log("data中的數據還不能加載出來:",this.title)},//初始化完成,監聽攔截加載完成,data中的數據可以加載出來created(){console.log("created:")console.log("data中的數據可以加載出來了",this.title)this.interId=setInterval(()=>{console.log("執行定時器中....")},1000)},//dom還沒有掛載到樹上beforeMount(){console.log("beforeMount:")console.log(document.getElementById("name"))},//dom已經掛載到樹上了mounted(){console.log("mounted:")console.log(document.getElementById("name"))},//銷毀,可以關閉定時器destroyed(){console.log("組件銷毀了...")clearInterval(this.interId)},} </script><style> </style>

16. 組件的通訊

16.1父組件給子組件傳值

子組件:通過props來接受外界傳遞到組件內部的值

<template><view>這是一個自定義組件 {{msg}}</view> </template><script>export default {props: ['msg']} </script><style> </style>

父組件:在使用login組件的時候傳遞值

<template><view><test :msg="msg"></test></view> </template><script>import test from "@/components/test/test.vue"export default {data () {return {msg: 'hello'}},components: {test}} </script>

16.2子組件給父組件傳值

子組件:通過$emit觸發事件進行傳遞參數

<template><view>這是一個自定義組件 {{msg}}<button type="primary" @click="sendMsg">給父組件傳值</button></view> </template><script>export default {data () {return {status: '打籃球'}},props: {msg: {type: String,value: ''}},methods: {sendMsg () {this.$emit('myEvent',this.status)}}} </script>

父組件:父組件定義自定義事件并接收參數【getMsg函數不能加()】

<template><view><test :msg="msg" @myEvent="getMsg"></test>這是子組件傳遞給父組件的值{{num}}</view> </template> <script>import test from "@/components/test/test.vue"export default {data () {return {msg: 'hello',num:0,}},methods: {getMsg (res) {this.num=resconsole.log(res)}},components: {test}} </script>

16.3兄弟組件通訊(先注冊事件,再觸發事件)

16.3.1全局事件與局部事件的區別

全局事件:uni.$emit();

局部事件:this.$emit()

在b組件里注冊全局事件,a組件點擊按鈕后就觸發該全局事件
a組件

<template><view>這是a組件,要修改b組件的值:<button @click="changeNumB">切換b組件的值</button></view> </template><script>export default{data(){return{}},methods:{changeNumB(){uni.$emit('changeNum',10)}}} </script><style> </style>

b組件

<template><view>這是b組件,b組件的值:{{num}}</view> </template><script>export default{data(){return {num:20}},created(){//注冊全局事件uni.$on('changeNum',(a)=>{this.num+=a})}} </script><style> </style>

首頁

<template><view class="content"><test-a></test-a><test-b></test-b></view> </template><script>import testA from '../components/a.vue'import testB from '../components/b.vue'export default {components:{'test-a':testA,'test-b':testB,},} </script><style>.content {display: flex;flex-direction: column;align-items: center;justify-content: center;}.logo {height: 200rpx;width: 200rpx;margin-top: 200rpx;margin-left: auto;margin-right: auto;margin-bottom: 50rpx;}.text-area {display: flex;justify-content: center;}.title {font-size: 36rpx;color: #8f8f94;} </style>

17. uni-ui的使用

uni-ui文檔

1、進入Grid宮格組件

2、使用HBuilderX導入該組件

3、導入該組件

import uniGrid from "@/components/uni-grid/uni-grid.vue" import uniGridItem from "@/components/uni-grid-item/uni-grid-item.vue"

4、注冊組件

components: {uniGrid,uniGridItem}

5、使用組件

<uni-grid :column="3"><uni-grid-item><text class="text">文本</text></uni-grid-item><uni-grid-item><text class="text">文本</text></uni-grid-item><uni-grid-item><text class="text">文本</text></uni-grid-item> </uni-grid>

總結

以上是生活随笔為你收集整理的【uni-app】uni-app的基础知识的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。