UniApp是一個基于Vue.js開發多端應用的框架,它可以讓開發者編寫一次代碼,同時適配iOS、Android、Web等多個平臺。
環境搭建:
UniApp基于Vue.js開發,所以需要先安裝Vue CLI
npm install -g @vue/cli
創建一個新的UniApp項目,名為"myapp"
vue create -p dcloudio/uni-preset-vue myapp
進入項目目錄,并運行以下命令啟動開發服務器:
cd myapp
npm run dev:mp-weixin
多端適配
基于flexbox的彈性布局來實現不同設備的適配
- display: flex;
- 在UniApp中使用rpx作為單位進行適配
<template><view class="container"><view class="box">1</view><view class="box">2</view><view class="box">3</view></view></template><style>.container {display: flex;flex-wrap: wrap;justify-content: space-between;
}.box {width: 200rpx; /* 在UniApp中使用rpx作為單位進行適配 */height: 200rpx;background-color: #f00;
}
</style>
條件編譯
UniApp提供了條件編譯的功能,可以根據不同平臺對代碼進行選擇性編譯
<template><view><!-- #ifdef MP-WEIXIN --><button @click="wechatLogin">微信登錄</button><!-- #endif --><!-- #ifdef H5 --><button @click="webLogin">網頁登錄</button><!-- #endif --><!-- ... --></view>
</template><script>
export default {methods: {wechatLogin() {// 微信登錄邏輯},webLogin() {// 網頁登錄邏輯},// ...}
}
</script>
跨端UI組件
UniApp內置了一些跨平臺的UI組件,使得開發者可以更方便地實現多端適配。
比如,可以使用uni-icons組件來顯示不同平臺的圖標。
<template><view><uni-icons :type="iconType"></uni-icons></view>
</template><script>
export default {data() {return {iconType: ''};},onLoad() {#ifdef MP-WEIXINthis.iconType = 'wechat';#endif#ifdef H5this.iconType = 'html5';#endif}
}
</script>