uni-app的基本使用
課程介紹:
基礎部分:
- 環境搭建
- 頁面外觀配置
- 數據綁定
- uni-app的生命周期
- 組件的使用
- uni-app中樣式學習
- 在uni-app中使用字體圖標和開啟scss
- 條件注釋跨端兼容
- uni中的事件
- 導航跳轉
- 組件創建和通訊,及組件的生命周期
- uni-app中使用uni-ui庫
項目:黑馬商城項目
uni-app介紹 官方網頁
uni-app
是一個使用 Vue.js 開發所有前端應用的框架,開發者編寫一套代碼,可發布到iOS、Android、H5、以及各種小程序(微信/支付寶/百度/頭條/QQ/釘釘)等多個平台。
即使不跨端,uni-app
同時也是更好的小程序開發框架。
具有vue和微信小程序的開發經驗,可快速上手uni-app
為什么要去學習uni-app?
相對開發者來說,減少了學習成本,因為只學會uni-app之后,即可開發出iOS、Android、H5、以及各種小程序的應用,不需要再去學習開發其他應用的框架,相對公司而言,也大大減少了開發成本。
環境搭建
安裝編輯器HbuilderX 下載地址
HBuilderX是通用的前端開發工具,但為uni-app
做了特別強化。
下載App開發版,可開箱即用
安裝微信開發者工具 下載地址
利用HbuilderX初始化項目
點擊HbuilderX菜單欄文件>項目>新建
選擇uni-app,填寫項目名稱,項目創建的目錄
運行項目
在菜單欄中點擊運行,運行到瀏覽器,選擇瀏覽器即可運行
在微信開發者工具里運行:進入hello-uniapp項目,點擊工具欄的運行 → 運行到小程序模擬器 → 微信開發者工具,即可在微信開發者工具里面體驗uni-app
在微信開發者工具里運行:進入hello-uniapp項目,點擊工具欄的運行 → 運行到手機或模擬器 → 選擇調式的手機
注意:
- 如果是第一次使用,需要先配置小程序ide的相關路徑,才能運行成功
- 微信開發者工具在設置中安全設置,服務端口開啟
介紹項目目錄和文件作用
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布局進行開發
全局配置和頁面配置
通過globalStyle進行全局配置
用於設置應用的狀態欄、導航條、標題、窗口背景色等。詳細文檔
屬性 | 類型 | 默認值 | 描述 |
---|---|---|---|
navigationBarBackgroundColor | HexColor | #F7F7F7 | 導航欄背景顏色(同狀態欄背景色) |
navigationBarTextStyle | String | white | 導航欄標題顏色及狀態欄前景顏色,僅支持 black/white |
navigationBarTitleText | String | 導航欄標題文字內容 | |
backgroundColor | HexColor | #ffffff | 窗口的背景色 |
backgroundTextStyle | String | dark | 下拉 loading 的樣式,僅支持 dark / light |
enablePullDownRefresh | Boolean | false | 是否開啟下拉刷新,詳見頁面生命周期。 |
onReachBottomDistance | Number | 50 | 頁面上拉觸底事件觸發時距頁面底部距離,單位只支持px,詳見頁面生命周期 |
創建新的message頁面
右鍵pages新建message目錄,在message目錄下右鍵新建.vue文件,並選擇基本模板
<template>
<view>
這是信息頁面
</view>
</template>
<script>
</script>
<style>
</style>
通過pages來配置頁面
屬性 | 類型 | 默認值 | 描述 |
---|---|---|---|
path | String | 配置頁面路徑 | |
style | Object | 配置頁面窗口表現,配置項參考 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"
}
}
}
}
]
配置tabbar
如果應用是一個多 tab 應用,可以通過 tabBar 配置項指定 tab 欄的表現,以及 tab 切換時顯示的對應頁。
Tips
- 當設置 position 為 top 時,將不會顯示 icon
- tabBar 中的 list 是一個數組,只能配置最少2個、最多5個 tab,tab 按數組的順序排序。
屬性說明:
屬性 | 類型 | 必填 | 默認值 | 描述 | 平台差異說明 |
---|---|---|---|---|---|
color | HexColor | 是 | tab 上的文字默認顏色 | ||
selectedColor | HexColor | 是 | tab 上的文字選中時的顏色 | ||
backgroundColor | HexColor | 是 | tab 的背景色 | ||
borderStyle | String | 否 | black | tabbar 上邊框的顏色,僅支持 black/white | App 2.3.4+ 支持其他顏色值 |
list | Array | 是 | tab 的列表,詳見 list 屬性說明,最少2個、最多5個 tab | ||
position | String | 否 | bottom | 可選值 bottom、top | top 值僅微信小程序支持 |
其中 list 接收一個數組,數組中的每個項都是一個對象,其屬性值如下:
屬性 | 類型 | 必填 | 說明 |
---|---|---|---|
pagePath | String | 是 | 頁面路徑,必須在 pages 中先定義 |
text | String | 是 | tab 上按鈕文字,在 5+APP 和 H5 平台為非必填。例如中間可放一個沒有文字的+號圖標 |
iconPath | String | 否 | 圖片路徑,icon 大小限制為40kb,建議尺寸為 81px * 81px,當 postion 為 top 時,此參數無效,不支持網絡圖片,不支持字體圖標 |
selectedIconPath | String | 否 | 選中時的圖片路徑,icon 大小限制為40kb,建議尺寸為 81px * 81px ,當 postion 為 top 時,此參數無效 |
案例代碼:
"tabBar": {
"list": [
{
"text": "首頁",
"pagePath":"pages/index/index",
"iconPath":"static/tabs/home.png",
"selectedIconPath":"static/tabs/home-active.png"
},
{
"text": "信息",
"pagePath":"pages/message/message",
"iconPath":"static/tabs/message.png",
"selectedIconPath":"static/tabs/message-active.png"
},
{
"text": "我們",
"pagePath":"pages/contact/contact",
"iconPath":"static/tabs/contact.png",
"selectedIconPath":"static/tabs/contact-active.png"
}
]
}
condition啟動模式配置
啟動模式配置,僅開發期間生效,用於模擬直達頁面的場景,如:小程序轉發后,用戶點擊所打開的頁面。
屬性說明:
屬性 | 類型 | 是否必填 | 描述 |
---|---|---|---|
current | Number | 是 | 當前激活的模式,list節點的索引值 |
list | Array | 是 | 啟動模式列表 |
list說明:
屬性 | 類型 | 是否必填 | 描述 |
---|---|---|---|
name | String | 是 | 啟動模式名稱 |
path | String | 是 | 啟動頁面路徑 |
query | String | 否 | 啟動參數,可在頁面的 onLoad 函數里獲得 |
組件的基本使用
uni-app提供了豐富的基礎組件給開發者,開發者可以像搭積木一樣,組合各種組件拼接稱自己的應用
uni-app中的組件,就像 HTML
中的 div
、p
、span
等標簽的作用一樣,用於搭建頁面的基礎結構
text文本組件的用法
001 - text 組件的屬性
屬性 | 類型 | 默認值 | 必填 | 說明 |
---|---|---|---|---|
selectable | boolean | false | 否 | 文本是否可選 |
space | string | . | 否 | 顯示連續空格,可選參數:ensp 、emsp 、nbsp |
decode | boolean | false | 否 | 是否解碼 |
text
組件相當於行內標簽、在同一行顯示- 除了文本節點以外的其他節點都無法長按選中
002 - 代碼案例
<view>
<!-- 長按文本是否可選 -->
<text selectable='true'>來了老弟</text>
</view>
<view>
<!-- 顯示連續空格的方式 -->
<view>
<text space='ensp'>來了 老弟</text>
</view>
<view>
<text space='emsp'>來了 老弟</text>
</view>
<view>
<text space='nbsp'>來了 老弟</text>
</view>
</view>
<view>
<text>skyblue</text>
</view>
<view>
<!-- 是否解碼 -->
<text decode='true'> < > & '    </text>
</view>
view視圖容器組件的用法
View 視圖容器, 類似於 HTML 中的 div
001 - 組件的屬性
002 - 代碼案例
<view class="box2" hover-class="box2_active">
<view class='box1' hover-class='active' hover-stop-propagation :hover-start-time="2000" :hover-stay-time='2000'>
</view>
</view>
button按鈕組件的用法
001 - 組件的屬性
屬性名 | 類型 | 默認值 | 說明 |
---|---|---|---|
size | String | default | 按鈕的大小 |
type | String | default | 按鈕的樣式類型 |
plain | Boolean | false | 按鈕是否鏤空,背景色透明 |
disabled | Boolean | false | 是否按鈕 |
loading | Boolean | false | 名稱是否帶 loading t圖標 |
button
組件默認獨占一行,設置size
為mini
時可以在一行顯示多個
002 - 案例代碼
<button size='mini' type='primary'>前端</button>
<button size='mini' type='default' disabled='true'>前端</button>
<button size='mini' type='warn' loading='true'>前端</button>
image組件的使用
image
圖片。
屬性名 | 類型 | 默認值 | 說明 | 平台差異說明 |
---|---|---|---|---|
src | String | 圖片資源地址 | ||
mode | String | 'scaleToFill' | 圖片裁剪、縮放的模式 |
Tips
<image>
組件默認寬度 300px、高度 225px;src
僅支持相對路徑、絕對路徑,支持 base64 碼;- 頁面結構復雜,css樣式太多的情況,使用 image 可能導致樣式生效較慢,出現 “閃一下” 的情況,此時設置
image{will-change: transform}
,可優化此問題。
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
uni-app中的數據綁定
在頁面中需要定義數據,和我們之前的vue一摸一樣,直接在data中定義數據即可
export default {
data () {
return {
msg: 'hello-uni'
}
}
}
插值表達式的使用
利用插值表達式渲染基本數據
<view>{{msg}}</view>
在插值表達式中使用三元運算
<view>{{ flag ? '我是真的':'我是假的' }}</view>
基本運算
<view>{{1+1}}</view>
v-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>
v-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>
uni中的事件
事件綁定
在uni中事件綁定和vue中是一樣的,通過v-on進行事件的綁定,也可以簡寫為@
<button @click="tapHandle">點我啊</button>
事件函數定義在methods中
methods: {
tapHandle () {
console.log('真的點我了')
}
}
事件傳參
默認如果沒有傳遞參數,事件函數第一個形參為事件對象
// template <button @click="tapHandle">點我啊</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) } }
uni的生命周期
應用的生命周期
生命周期的概念:一個對象從創建、運行、銷毀的整個過程被成為生命周期。
生命周期函數:在生命周期中每個階段會伴隨着每一個函數的觸發,這些函數被稱為生命周期函數
uni-app
支持如下應用生命周期函數:
函數名 | 說明 |
---|---|
onLaunch | 當uni-app 初始化完成時觸發(全局只觸發一次) |
onShow | 當 uni-app 啟動,或從后台進入前台顯示 |
onHide | 當 uni-app 從前台進入后台 |
onError | 當 uni-app 報錯時觸發 |
頁面的生命周期
uni-app
支持如下頁面生命周期函數:
函數名 | 說明 | 平台差異說明 | 最低版本 |
---|---|---|---|
onLoad | 監聽頁面加載,其參數為上個頁面傳遞的數據,參數類型為Object(用於頁面傳參),參考示例 | ||
onShow | 監聽頁面顯示。頁面每次出現在屏幕上都觸發,包括從下級頁面點返回露出當前頁面 | ||
onReady | 監聽頁面初次渲染完成。 | ||
onHide | 監聽頁面隱藏 | ||
onUnload | 監聽頁面卸載 |
下拉刷新
開啟下拉刷新
在uni-app中有兩種方式開啟下拉刷新
- 需要在
pages.json
里,找到的當前頁面的pages節點,並在style
選項中開啟enablePullDownRefresh
- 通過調用uni.startPullDownRefresh方法來開啟下拉刷新
通過配置文件開啟
創建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
}
}
通過API開啟
uni.startPullDownRefresh()
監聽下拉刷新
通過onPullDownRefresh可以監聽到下拉刷新的動作
export default {
data () {
return {
arr: ['前端','java','ui','大數據']
}
},
methods: {
startPull () {
uni.startPullDownRefresh()
}
},
onPullDownRefresh () {
console.log('觸發下拉刷新了')
}
}
關閉下拉刷新
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>
上拉加載
通過在pages.json文件中找到當前頁面的pages節點下style中配置onReachBottomDistance可以設置距離底部開啟加載的距離,默認為50px
通過onReachBottom監聽到觸底的行為
<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','大數據','前端','java','ui','大數據']
}
},
onReachBottom () {
console.log('觸底了')
}
}
</script>
<style>
view{
height: 100px;
line-height: 100px;
}
</style>
網絡請求
在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請求
數據緩存
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>
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>
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>
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>
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>
uni.removeStorageSync
從本地緩存中同步移除指定 key。
代碼演示
<template>
<view>
<button type="primary" @click="removeStorage">刪除數據</button>
</view>
</template>
<script>
export default {
methods: {
removeStorage () {
uni.removeStorageSync('id')
}
}
}
</script>
上傳圖片、預覽圖片
上傳圖片
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,
success: res=>{
this.imgArr = res.tempFilePaths
}
})
}
}
}
</script>
預覽圖片
結構
<view>
<image v-for="item in imgArr" :src="item" @click="previewImg(item)" :key="item"></image>
</view>
預覽圖片的方法
previewImg (current) {
uni.previewImage({
urls: this.imgArr,
current
})
}
條件注釋實現跨段兼容
條件編譯是用特殊的注釋作為標記,在編譯時根據這些特殊的注釋,將注釋里面的代碼編譯到不同平台。
**寫法:**以 #ifdef 加平台標識 開頭,以 #endif 結尾。
平台標識
值 | 平台 | 參考文檔 |
---|---|---|
APP-PLUS | 5+App | HTML5+ 規范 |
H5 | H5 | |
MP-WEIXIN | 微信小程序 | 微信小程序 |
MP-ALIPAY | 支付寶小程序 | 支付寶小程序 |
MP-BAIDU | 百度小程序 | 百度小程序 |
MP-TOUTIAO | 頭條小程序 | 頭條小程序 |
MP-QQ | QQ小程序 | (目前僅cli版支持) |
MP | 微信小程序/支付寶小程序/百度小程序/頭條小程序/QQ小程序 |
組件的條件注釋
代碼演示
<!-- #ifdef H5 -->
<view>
h5頁面會顯示
</view>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view>
微信小程序會顯示
</view>
<!-- #endif -->
<!-- #ifdef APP-PLUS -->
<view>
app會顯示
</view>
<!-- #endif -->
api的條件注釋
代碼演示
onLoad () {
//#ifdef MP-WEIXIN
console.log('微信小程序')
//#endif
//#ifdef H5
console.log('h5頁面')
//#endif
}
樣式的條件注釋
代碼演示
/* #ifdef H5 */
view{
height: 100px;
line-height: 100px;
background: red;
}
/* #endif */
/* #ifdef MP-WEIXIN */
view{
height: 100px;
line-height: 100px;
background: green;
}
/* #endif */
uni中的導航跳轉
利用navigator進行跳轉
navigator詳細文檔:文檔地址
跳轉到普通頁面
<navigator url="/pages/about/about" hover-class="navigator-hover">
<button type="default">跳轉到關於頁面</button>
</navigator>
跳轉到tabbar頁面
<navigator url="/pages/message/message" open-type="switchTab">
<button type="default">跳轉到message頁面</button>
</navigator>
利用編程式導航進行跳轉
利用navigateTo進行導航跳轉
保留當前頁面,跳轉到應用內的某個頁面,使用uni.navigateBack
可以返回到原頁面。
<button type="primary" @click="goAbout">跳轉到關於頁面</button>
通過navigateTo方法進行跳轉到普通頁面
goAbout () {
uni.navigateTo({
url: '/pages/about/about',
})
}
通過switchTab跳轉到tabbar頁面
跳轉到tabbar頁面
<button type="primary" @click="goMessage">跳轉到message頁面</button>
通過switchTab方法進行跳轉
goMessage () {
uni.switchTab({
url: '/pages/message/message'
})
}
redirectTo進行跳轉
關閉當前頁面,跳轉到應用內的某個頁面。
<!-- template -->
<button type="primary" @click="goMessage">跳轉到message頁面</button>
<!-- js -->
goMessage () {
uni.switchTab({
url: '/pages/message/message'
})
}
通過onUnload測試當前組件確實卸載
onUnload () {
console.log('組件卸載了')
}
導航跳轉傳遞參數
在導航進行跳轉到下一個頁面的同時,可以給下一個頁面傳遞相應的參數,接收參數的頁面可以通過onLoad生命周期進行接收
傳遞參數的頁面
goAbout () {
uni.navigateTo({
url: '/pages/about/about?id=80',
});
}
接收參數的頁面
<script>
export default {
onLoad (options) {
console.log(options)
}
}
</script>
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>
組件的生命周期函數
beforeCreate | 在實例初始化之后被調用。詳見 | ||
---|---|---|---|
created | 在實例創建完成后被立即調用。詳見 | ||
beforeMount | 在掛載開始之前被調用。詳見 | ||
mounted | 掛載到實例上去之后調用。詳見 注意:此處並不能確定子組件被全部掛載,如果需要子組件完全掛載之后在執行操作可以使用$nextTick Vue官方文檔 |
||
beforeUpdate | 數據更新時調用,發生在虛擬 DOM 打補丁之前。詳見 | 僅H5平台支持 | |
updated | 由於數據更改導致的虛擬 DOM 重新渲染和打補丁,在這之后會調用該鈎子。詳見 | 僅H5平台支持 | |
beforeDestroy | 實例銷毀之前調用。在這一步,實例仍然完全可用。詳見 | ||
destroyed | Vue 實例銷毀后調用。調用后,Vue 實例指示的所有東西都會解綁定,所有的事件監聽器會被移除,所有的子實例也會被銷毀。詳見 |
組件的通訊
父組件給子組件傳值
通過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>
子組件給父組件傳值
通過$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>
父組件定義自定義事件並接收參數
<template>
<view>
<test :msg="msg" @myEvent="getMsg"></test>
</view>
</template>
<script>
import test from "@/components/test/test.vue"
export default {
data () {
return {
msg: 'hello'
}
},
methods: {
getMsg (res) {
console.log(res)
}
},
components: {test}
}
</script>
兄弟組件通訊
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>
黑馬商城實戰項目
項目搭建
利用HBuilder X創建基本項目結構
運行項目
整理基本項目結構,並修改窗口外觀
"globalStyle": { "navigationBarTextStyle": "white", "navigationBarTitleText": "黑馬商城", "navigationBarBackgroundColor": "#1989fa", "backgroundColor": "#F8F8F8" }
配置tabbar
創建tabbar對應的四個頁面和圖標准備好
將頁面路徑配置到pages.json中的pages數組中
"pages": [ //pages數組中第一項表示應用啟動頁,參考:https://uniapp.dcloud.io/collocation/pages { "path": "pages/index/index" }, { "path": "pages/member/member" }, { "path": "pages/cart/cart" }, { "path": "pages/search/search" } ]
配置tabbar
{ "tabBar": { "list": [ { "pagePath":"pages/index/index", "text":"首頁", "iconPath":"static/icon/home.png", "selectedIconPath":"static/icon/home-active.png" }, { "pagePath":"pages/member/member", "text":"會員", "iconPath":"static/icon/member.png", "selectedIconPath":"static/icon/member-active.png" }, { "pagePath":"pages/cart/cart", "text":"購物車", "iconPath":"static/icon/cart.png", "selectedIconPath":"static/icon/cart-active.png" }, { "pagePath":"pages/search/search", "text":"搜索", "iconPath":"static/icon/search.png", "selectedIconPath":"static/icon/search-active.png" } ] } }
獲取輪播圖數據
封裝uni.request請求,並掛在到全局
創建util》api.js
// 封裝get請求 const baseUrl = "http://localhost:8082" export const myRequest = (options)=>{ return new Promise((resolve,reject)=>{ uni.request({ method: options.method, data: options.data, url: baseUrl+options.url, success(res) { if(res.data.status !== 0) { return uni.showToast({ title: '獲取數據失敗' }) } resolve(res) }, fail(err) { uni.showToast({ title: '獲取數據失敗' }) reject(err) } }) }) }
在main.js中導入並掛載到全局
import { myRequest } from './util/api.js' Vue.prototype.$myRequest = myReques
獲取輪播圖的數據
定義獲取輪播圖的方法
methods: { async getSwipers () { const res = await this.$myRequest({ method: 'GET', url: '/api/getlunbo' }) this.swipers = res.data.message } }
在onLoad中調用該方法
this.getSwipers()
實現輪播圖的結構和數據渲染
定義輪播圖的基本結構
<swiper class="swiper" indicator-dots :autoplay="true" :interval="2000" circular> <swiper-item v-for="item in swipers" :key="item.id"> <image :src="item.img"></image> </swiper-item> </swiper>
樣式,在工具中安裝scss
<style lang="scss"> .home{ swiper{ height: 380rpx; image{ width: 750rpx; height: 380rpx; } } } </style>
實現菜單導航結構
引入字體圖標初始化樣式
<style>
@font-face {font-family: "iconfont";
src: url('~@/static/fonts/iconfont.eot?t=1576335469449'); /* IE9 */
src: url('~@/static/fonts/iconfont.eot?t=1576335469449#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAVMAAsAAAAAChwAAAT/AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCDKAqHQIYhATYCJAMUCwwABCAFhG0HUBurCFGUTk6f7EeBu6eIlFFajBY208XLlGHx/6/hiYfvx76d+2xFJLlUn75pp4tCoyQ8NgiJUJjuJfzNpSrpXIDoeDbs3GjyH7Lfv+zTy1mok+GyEhYAW8AKaPvz/6eeG1QvDUo6SQW8bE4KYTDSMRj1R/5x7/TP88Dmo7Jc/misYXOelwWYYEBjbGxrAQ7KEvQW8SwuJBO4nkCvRQ21q/PbB5hXQLdAvDU6gHmbRQnhhG598xlb1lEvsu70PvEBfFU/H/+hF1IkNYO+149nMRz+6v7/fwrv4JAqI6T5uXCbRMYWUIhnX8+tKT22ZUrvJ3PaCdCNryR+Sb2RfRPT+c9kbdF0s788siIRDWj6GXkWL/ySEsVkfsmyftoYKiIZsiQfJ+Y2ll7MgdgDiE/AMF+CumLWsCSpdFXpjsNkefoatW8WSY8xapRhreWm1a9vWvVEM6edaQdPapImTzTLLG4BwEBG/HJsK4bVEKkStJbxbUYy3othvO2ofJA7jBARcUZ4illDuEL29TB2C/3AGWj4WUfGYbG25LTICaEk1jWBR8KWC0bqQJ+EjJYmOnvisiHzqtifvZ08X7NYzBaJWAJBglDIRIi3Fd/C3cbZjqEKvkh9Qmx2SKCgMAhD15VHVkCQMCWOP72YnLB0euHUpROzJ/PEYiR6wxK8ShC+ZsryVibGlbIzorOjqRKnhwyOKTIlMRoPSLgMlYvInDIKdwsQ8K2YbO2PReRsyxzZvrK0dWxUYUrIE2sPj8+sHNw6tUVhj0AgslvelUfhDnNG4k0YwgedbyX/ovPRL8SnqwOt/atMII/RGGMacyXGJOaq+MtGYDFMOL1Hk8OSJdfqARNMZkPmnDVh5DP0bjDpx6XAB6RO0JkqM4F0fNSNZMKXB20QqI//n+swdzCvnv1/JszOzMEszPsskD8RZtrarNB14gGhubjWlduokVnWD9e9PyCQd1jtvPjStKTGs6VZFT/xjhhW0hpkG6PoC0wW8iGUrPK9prFY4AM+9GF8APhKfIvr5tct+IoAxU/eE3ILa4yrDxTgUfkrG0lPTtshU4pGtXT9UJqywWkDhzyi/5ka15D+WlPn1Gd+QYF7s0j3dXTuS0oStZLum6on86NOwIbPcydIP3+STiDFaYk1Z6WFLPt7b7M6EhMA+Gr+qtDilfia4mPFr0p8JZUS973QHulzYJxsPjJ6xdeW7Wd75WHHrZsGDXaUb1hacCuQVmrOkt1DjdgTxSeY3EcWDqCzRLxB9PmH2DNplYhzhCDbNLfzY7dKy1jb/dqNFfBTXbWg8vhWsH1JP9IN0VQmIcif4isHay1vtVDzNIiyxeirbpZ0JKEXg3QAAqN+8jFMLN9E6DZhQtJlAbJuS2ght6DqcwRNt1Potelicp8xbEqUHmz4IBCGfUIy6DtkwyZoIb+hmvQLzXAQoddNbM3ZZyWKFk+YAqEYwxGayJZKsMuiVnxH2ucBW+Uq94m4MkHstjrO5AWVxHkMqPq6J6JQsS3wnGxGeW7RsU0pklYi4rbbbeV3plZkC1h0iZGAIDEUGkFGxCopubpYdL3/DtG8XIBDSn4knxBWMbWjrpZODPRCU8YqWZfGlT6tRwjFOynMKqBz6iI5xizk/FulSES0JCkizrY2q6Tialrl64ppLD0VysKcNVLkKFGjae8S40w5K14OB+WS9lKjkR/YgsrZsRnZzAAA') format('woff2'),
url('~@/static/fonts/iconfont.woff?t=1576335469449') format('woff'),
url('~@/static/fonts/iconfont.ttf?t=1576335469449') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
url('~@/static/fonts/iconfont.svg?t=1576335469449#iconfont') format('svg'); /* iOS 4.1- */
}
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-shipin:before {
content: "\f0024";
}
.icon-tupian:before {
content: "\e650";
}
.icon-guanyuwomen:before {
content: "\e608";
}
.icon-ziyuan:before {
content: "\e60d";
}
</style>
完成菜單導航基本結構
<view class="nav">
<view class="item">
<view class="iconfont icon-ziyuan"></view>
<text>黑馬超市</text>
</view>
<view class="item">
<view class="iconfont icon-tupian"></view>
<text>聯系我們</text>
</view>
<view class="item">
<view class="iconfont icon-guanyuwomen"></view>
<text>社區圖片</text>
</view>
<view class="item">
<view class="iconfont icon-shipin"></view>
<text>視頻專區</text>
</view>
</view>
菜單導航樣式
.nav{
display: flex;
align-items: center;
.item{
width: 25%;
text-align: center;
view{
background: $shop-color;
line-height: 120rpx;
width: 120rpx;
height: 120rpx;
border-radius: 90px;
margin:10px auto;
}
text{
font-size: 15px;
}
}
.iconfont{
font-size: 25px;
color: #fff;
height: 50px;
}
.icon-tupian{
font-size: 20px;
}
}
實現推薦商品列表
定義基本結構
<view class="hot_goods">
<view class="tit">推薦商品</view>
<!-- 一般用法 -->
<view class="goods_list">
<view class="goods_item">
<image></image>
<view class="price">
<text>1299</text>
<text>12990</text>
</view>
<view class="name">華為(HUAWEI)榮耀6Plus 16G雙4G版</view>
</view>
</view>
</view>
美化樣式
.hot_goods {
background: #eee;
.tit{
border-top: 2px solid #eee;
border-bottom: 2px solid #eee;
margin-top: 20px;
margin-bottom: 3px;
color: $shop-color;
height: 50px;
line-height: 50px;
text-align: center;
letter-spacing: 20px;
background: #fff;
}
.goods_list {
display: flex;
padding: 0 15rpx;
justify-content: space-between;
overflow: hidden;
flex-wrap: wrap;
.goods_item {
width: 355rpx;
margin-bottom: 15rpx;
background: #fff;
padding: 10px;
box-sizing: border-box;
image{
height: 150px;
width: auto;
mix-width:160px;
margin: 10px auto;
}
.price{
font-size: 18px;
color: red;
padding: 8px 0;
text:nth-child(2){
color: #ccc;
text-decoration: line-through;
margin-left: 10px;
font-size: 13px;
}
}
.name {
font-size: 14px;
}
}
}
}
獲取數據
定義獲取數據的方法
// 獲取推薦商品 async getGoods () { const res = await this.$myRequest({ url: '/api/getgoods?pageindex=1' }) this.goods = res.data.message }
在onLoad生命周期中調用該方法
this.getGoods()
渲染數據
通過v-for渲染數據
<view class="hot_goods"> <view class="tit">推薦商品</view> <!-- 一般用法 --> <view class="goods_list"> <view class="goods_item" v-for="item in goods" :key="item.id"> <image :src="item.img_url"></image> <view class="price"> <text>{{item.sell_price}}</text> <text>{{item.market_price}}</text> </view> <view class="name">{{item.title}}</view> </view> </view> </view>
完成黑馬超市頁面
改造導航菜單
定義數據
navs: [ { icons: "iconfont icon-ziyuan", title: "黑馬超市", path: "/pages/goods/list" }, { icons: "iconfont icon-tupian", title: "社區圖片", path: "/pages/pics/pics" }, { icons: "iconfont icon-guanyuwomen", title: "聯系我們", path: "/pages/contact/contact" }, { icons: "iconfont icon-shipin", title: "學習視頻", path: "/pages/videos/videos" } ]
渲染數據
<view class="nav"> <view class="item" v-for="(item,index) in navs" :key="index"> <view :class="item.icons"></view> <text>{{item.title}}</text> </view> </view>
給導航菜單注冊點擊事件
<view class="goods_item" v-for="item in goods" :key="item.id">
定義跳轉的方法
goNavigator (url) { uni.navigateTo({ url }) }
創建黑馬超市頁面
- 創建頁面,goods>list.vue
- 將頁面路勁配置到pages文件中,修改標題
封裝商品列表組件
在components下面創建goods>list.vue
<template> <view class="goods_list"> <view class="goods_item" v-for="item in goods" :key="item.id"> <image :src="item.img_url"></image> <view class="price"> <text>{{item.sell_price}}</text> <text>{{item.market_price}}</text> </view> <view class="name">{{item.title}}</view> </view> </view> </template> <script> export default { props:{ goods:Array } } </script> <style lang="scss"> .goods_list { display: flex; padding: 0 15rpx; justify-content: space-between; overflow: hidden; flex-wrap: wrap; .goods_item { width: 355rpx; margin-bottom: 15rpx; background: #fff; padding: 10px; box-sizing: border-box; image{ height: 150px; width: 150px; display: block; margin: 10px auto; } .price{ font-size: 18px; color: red; padding: 8px 0; text:nth-child(2){ color: #ccc; text-decoration: line-through; margin-left: 10px; font-size: 13px; } } .name { font-size: 14px; } } } </style>
在首頁引入該組件
import goodsList from "../../components/goods-list/index.vue" components: { "goods-list":goodsList }
使用組件並將數據傳遞到組件內部
<goods-list :goods="goods"></goods-list>
渲染商品列表
定義獲取商品列表數據的方法並調用
<script> export default { data () { return { goods: [] } }, methods: { async getGoods () { const res = await this.$myRequest({ url: '/api/getgoods?pageindex=1' }) this.goods = res.data.message }, }, onLoad () { this.getGoods() } } </script>
引入商品組件並使用
<template> <view class="goods_list"> <goods-list :goods="goods"></goods-list> </view> </template> <script> import goodsList from "../../components/goods-list/index.vue" export default { components: { "goods-list": goodsList } } </script>
實現上拉加載更多
通過onReachBottom來監聽觸底
onReachBottom () { this.pageindex++ this.getGoods() }
修改給goods賦值
this.goods = [...this.goods,...res.data.message]
動態顯示底線
通過onReachBottom監聽是否還有更多
if(this.pageindex*10>this.goods.length) return this.flag = true
通過v-if控制底線
<view class="over_line" v-if="flag">----------我是有底線的----------</view>
實現下拉刷新
通過onPullDownRefresh進行下拉刷新的操作
onPullDownRefresh() { this.goods = [] this.pageindex = 1 this.flag = false setTimeout(()=>{ this.getGoods(()=>{ uni.stopPullDownRefresh() }) },1000) }
關於我們
實現社區圖片
實現資訊列表
實現列表項的結構和樣式
結構
<view class="news_item">
<image src="../../static/logo.png"></image>
<view class="content">
<view class="tit">1季度多家房企利潤跌幅超50% 去庫存促銷戰打響</view>
<view class="info">
<text>發表時間:2019-12-23</text>
<text>瀏覽:1次</text>
</view>
</view>
</view>
樣式
.news{
.news_item{
display: flex;
padding: 5px 10px;
border-bottom: 3px solid $shop-color;
image{
width: 300rpx;
height: 150rpx;
}
.content {
padding: 5px 10px;
position: relative;
.tit{
font-size: 30rpx;
}
.info{
font-size: 26rpx;
position: absolute;
left: 10px;
bottom: 5px;
text:nth-child(2){
margin-left: 20px;
}
}
}
}
}
封裝為組件
創建news-item.vue
<template>
<view>
<view class="news_item" v-for="item in data" :key="item.id">
<image :src="item.img_url"></image>
<view class="content">
<view class="tit">{{item.title}}</view>
<view class="info">
<text>發表時間:{{item.add_time | formatDate}}</text>
<text>瀏覽:{{item.click+123}}次</text>
</view>
</view>
</view>
</view>
</template>
<script>
export default {
props: ['data'],
filters:{
formatDate(data){
const date = new Date(data)
console.log(date)
const day = date.getMonth().toString().padStart(2,'0')+'-'+date.getDay().toString().padStart(2,'0')
return date.getFullYear()+'-'+day
}
}
}
</script>
<style lang="scss">
.news_item{
display: flex;
padding: 5px 10px;
border-bottom: 1rpx solid $shop-color;
image{
max-width: 200rpx;
min-width: 200rpx;
height: 150rpx;
}
.content {
padding: 5px 10px;
position: relative;
.tit{
font-size: 30rpx;
}
.info{
font-size: 26rpx;
position: absolute;
left: 10px;
bottom: 5px;
text:nth-child(2){
margin-left: 20px;
}
}
}
}
</style>
在新聞頁面導入並使用
<template>
<view class="news">
<new-item :data="newsList"></new-item>
</view>
</template>
<script>
import newItem from '../../components/new-item/new-item.vue'
export default {
data() {
return {
newsList: []
}
},
methods: {
async getNewsList () {
const res = await this.$myRequest({
url:'/api/getnewslist'
})
this.newsList = res.data.message
}
},
onLoad () {
this.getNewsList()
},
components: {
"new-item":newItem
}
}
</script>
<style lang="scss">
</style>
點擊列表進入詳情
點擊子組件列表項通過this.$emit觸發父組件的方法
navigatorTo (item) { this.$emit('clickItem',item) }
父組件通過注冊clickItem事件及事件函數實現跳轉操作
<template> <view class="news"> <new-item :data="newsList" @clickItem="goDetail"></new-item> </view> </template> <script> export default { methods: { goDetail (data) { console.log(data) uni.navigateTo({ url: '/pages/news-detail/news-detail' }) } } } </script>
新建/pages/news-detail/news-detail頁面
實現資訊詳情
實現基本結構
<template>
<view class="news_detail">
<view class="news_title">
標題
</view>
<view class="info">
<text>發表時間:</text>
<text>瀏覽:</text>
</view>
<view class="content">
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
}
}
</script>
<style lang="scss">
.news_detail {
padding: 15rpx;
.news_title{
text-align: center;
font-size: 32rpx;
}
.info{
font-size: 28rpx;
display: flex;
justify-content: space-between;
}
}
</style>
獲取詳情的數據
methods: {
async getNewsDetail(id){
const res = await this.$myRequest({
url: '/api/getnew/'+id
})
console.log(res)
this.newsDetail = res.data.message[0]
}
},
onLoad (options){
this.getNewsDetail(options.id)
}
實現詳情的渲染
<view class="news_title">
{{newsDetail.title}}
</view>
<view class="info">
<text>發表時間:{{newsDetail.add_time | formatDate}}</text>
<text>瀏覽:{{newsDetail.click}}</text>
</view>
<view class="content">
<rich-text :nodes="newsDetail.content"></rich-text>
</view>
實現商品詳情頁
商品列表注冊點擊事件
<template>
<view class="goods_list">
<view @click="itemClick(item)" class="goods_item" v-for="item in goods" :key="item.id">
</view>
</view>
</template>
<script>
export default {
props:{
goods:Array
},
methods: {
itemClick(item) {
this.$emit('itemClick',item)
}
}
}
</script>
父組件綁定自定義事件進行跳轉
<goods-list @itemClick="godetail" :goods="goods"></goods-list>
godetail (item) {
uni.navigateTo({
url: '/pages/goods-detail/goods-detail?id='+item.id
})
}
創建商品詳情頁
獲取詳情輪播圖數據
methods: {
async getDetail(){
const res = await this.$myRequest({
url:'/api/getthumimages/'+this.id
})
console.log(res)
}
},
onLoad(options){
this.id = options.id
this.getDetail()
}
渲染輪播圖
<swiper indicator-dots>
<swiper-item v-for="item in swipers" :key="item.src">
<image :src="item.src"></image>
</swiper-item>
</swiper>
<style lang="scss">
.goods_detail{
swiper{
height: 700rpx;
image{
width: 100%;
height: 100%;
}
}
}
</style>
獲取商品信息
methods: {
async getDetailInfo () {
const res = await this.$myRequest({
url:'/api/goods/getinfo/'+this.id
})
this.info = res.data.message[0]
}
},
onLoad(options){
this.id = options.id
this.getDetailInfo()
}