当前位置:网站首页>uni-app
uni-app
2022-07-25 08:27:00 【Sports programmer】
Catalog
Use the visual interface to create
project window Configuration of
project pages、tabBar Configuration of
Message pop-up confirmation box
Pop up the operation box at the bottom
Run as H5 when , Set up proxy Agents solve cross domain problems
API Conditional compilation of
Conditional compilation of components
Conditional compilation of styles
Introduce common websites
Official website address :uni-app Official website
Plug-in address : DCloud Plug in market
uni-ui Address : uni-ui - DCloud Plug in market
Be careful :
- because
uni-niUsed inscss, So you need to install sass and sass-loader, however sass-loader Please use less than @11.0.0 Version of , Reference resources @dcloudio/uni-ui - npm uni-uiRelated components can use easycom (opens new window) Component mode to load , Put them insrc/componentsUnder the directory , There is no need to import , It can be directly used as a label
Create a project and run
Use the visual interface to create
Because the official website documents have been described in great detail , I won't repeat it here , Check the official website by yourself
Reference resources : uni-app Official website
Use vue-cli establish
ditto , Check the official website by yourself , But be careful , Global installation vue-cli The version should be consistent with the official website
Reference resources : uni-app Official website
Generate project steps
- Switch the terminal to non Chinese Directory
- Execute... In the terminal
vue create -p dcloudio/uni-preset-vue uni-shopInstructions - choice
Default template
# Run the project steps
- Switch the terminal to the project root directory
uni-shop - Run at terminal
npm run dev:mp-weixin - open
WeChat developer tools, Then select import - Import Directory selection
uni-shop/dist/dev/mp-weixin - At this point, you can see the effect
Run the command
Run as Wechat applet
npm run dev:mp-weixin // function , After operation , take dist/dev/mp-weixin Open with wechat developer tool
npm run build:mp-weixin // pack , After packing , Directory in dist/build/mp-weixin
Run as H5
npm run dev:h5 // function
npm run build:h5 // pack , The project directory is in dist/build/H5project window Configuration of
Realization effect
Refer to the pictures in the project implementation effect
Implementation steps
- stay
src/pages.jsonItems configured under the directory window(globalStyle)
{
"globalStyle": {
"navigationBarTextStyle": "white",
"navigationBarTitleText": " Project name ",
"navigationBarBackgroundColor": "#c00000",
"backgroundColor": "#F8F8F8"
}
}project pages、tabBar Configuration of
Reference address : uni-app Official website
Implementation steps
stay
src/pagesDirectoryhome/index.vue、category/index.vue、cart/index.vue、my/index.vuestay
src/pages.jsonItems configured under the directory tabBar
{
"pages": [
//pages The first item in the array represents the application startup page , Reference resources :https://uniapp.dcloud.io/collocation/pages
{
"path": "pages/home/index",
"style": {
"navigationBarTitleText": " home page "
}
},
{
"path": "pages/category/index",
"style": {
"navigationBarTitleText": " classification "
}
},
{
"path": "pages/cart/index",
"style": {
"navigationBarTitleText": " The shopping cart "
}
},
{
"path": "pages/my/index",
"style": {
"navigationBarTitleText": " my "
}
}
],
"tabBar": {
"selectedColor": "#c00000",
"backgroundColor": "#ffffff",
"list": [
{
"pagePath": "pages/home/index",
"iconPath": "static/tab_icons/home.png",
"selectedIconPath": "static/tab_icons/home-active.png",
"text": " home page "
},
{
"pagePath": "pages/category/index",
"iconPath": "static/tab_icons/cate.png",
"selectedIconPath": "static/tab_icons/cate-active.png",
"text": " classification "
},
{
"pagePath": "pages/cart/index",
"iconPath": "static/tab_icons/cart.png",
"selectedIconPath": "static/tab_icons/cart-active.png",
"text": " The shopping cart "
},
{
"pagePath": "pages/my/index",
"iconPath": "static/tab_icons/my.png",
"selectedIconPath": "static/tab_icons/my-active.png",
"text": " my "
}
]
}
}Project subcontracting
We all know that we have developed small programs , To optimize the download and startup speed of small programs . It will be divided into main contracting and subcontracting
The so-called main package , That is, the default startup page /TabBar page , And some public resources are required for all subcontracts /JS Script ; Subcontracting is based on pages.json The configuration of
Official documents :uni-app Official website
Subcontracting steps
1. stay src Create in folder subPkg Folder , And pages At the same level , The name depends on the individual
2. stay subPkg Create in folder pageA/idnex.vue and pageB/index.vue file
3. stay pages.json Use in subPackages introduce , Note here that it is the same as pages At the same level
{
"pages": [{ // Main package file
"path": "pages/index/index",
"style": { ...}
}, {
"path": "pages/login/login",
"style": { ...}
}],
"subPackages": [{ // Subcontract documents
"root": "subPkg", // Subcontracting folder
"pages": [{
"path": "pageA/index", // Subcontract the following page path
"style": { ...}
}]
}, {
"root": "subPkg",
"pages": [{
"path": "pageB/index",
"style": { ...}
}]
}],
}Be careful : .json No comments can be written in the file , I'm here to make it easy for you to distinguish
Basic content
Life cycle
Official website address : Page introduction | uni-app Official website
uni-app It uses Vue2 The grammar of , But it's different , Here are some examples
Official website address : Getting started with components | uni-app Official website
View container
Official website address : uni-app Official website
Be careful :uni The view container used is view , Not at all div, It's similar to the tradition html Medium div, It's used to wrap various elements
Form components
Official address :button | uni-app Official website
It includes input box 、form Forms 、button Button, etc .
Routing jump
Route jump is divided into many ways
The first one is navigator label
Official website address :navigator | uni-app Official website
This component is similar to HTML Medium <a> Components , But you can only jump to the local page . The target page must be in pages.json Register in .
<navigator url="navigate/navigate?title=navigate" hover-class="navigator-hover">
<button type="default"> Jump to a new page </button>
</navigator>The second kind API The way
Official website address : uni.navigateTo(OBJECT) | uni-app Official website
uni.navigateTo(OBJECT)
Keep the current page , Jump to a page in the app , Use uni.navigateBack You can go back to the original page .
Be careful :
- The parameters passed must be in the page life cycle onLoad In order to receive
- The page Jump path has hierarchical restrictions , You can't jump to new pages without restrictions
- Jump to tabBar The page can only use switchTab Jump
- route API The target page must be in pages.json Registered in vue page .
// Jump to... On the start page test.vue Page and pass parameters
uni.navigateTo({
url: 'test?id=1&name=uniapp'
});
// stay test.vue The page accepts parameters
export default {
onLoad: function (option) { //option by object type , Will serialize the parameters passed from the previous page
console.log(option.id); // Print out the parameters passed from the previous page .
console.log(option.name); // Print out the parameters passed from the previous page .
}
#uni.navigateBack(OBJECT)
Close current page , Go back to the previous page or multi-level page . It can be done by getCurrentPages() Get the current page stack , Decide how many layers you need to go back .
// Be careful : call navigateTo When jumping , The page that calls this method will be added to the stack , and redirectTo Methods do not . See the example code below
// Here is A page
uni.navigateTo({
url: 'B?id=1'
});
// Here is B page
uni.navigateTo({
url: 'C?id=1'
});
// stay C In page navigateBack, Will return A page
uni.navigateBack({
delta: 2
});uni.redirectTo(OBJECT)
Close current page , Jump to a page in the app
uni.redirectTo({
url: 'test?id=1'
});#uni.reLaunch(OBJECT)
Close all pages , Open to a page in the app .
Be careful : If called uni.preloadPage(OBJECT) (opens new window) Will not close , Just trigger the lifecycle onHide
uni.reLaunch({
url: 'test?id=1'
});
export default {
onLoad: function (option) {
console.log(option.id);
}
}#uni.switchTab(OBJECT)
Jump to tabBar page , And shut down all the others tabBar page .
Be careful : If called uni.preloadPage(OBJECT) (opens new window) Will not close , Just trigger the lifecycle onHide
pages.json
{
"tabBar": {
"list": [{
"pagePath": "pages/index/index",
"text": " home page "
},{
"pagePath": "pages/other/other",
"text": " other "
}]
}
}
other.vue
uni.switchTab({
url: '/pages/index/index'
});storage
Official website address : uni.setStorage(OBJECT) @setstorage | uni-app Official website
uni.setStorageSync
Store data locally
uni.setStorageSync('storage_key', 'hello');uni.getStorageSync
Get the specified from the local cache synchronously key Corresponding content
uni.getStorageSync('storage_key');uni.removeStorageSync
Remove the specified from the local cache synchronously key
uni.removeStorageSync('storage_key');The drop-down refresh
Official website address : onPullDownRefresh | uni-app Official website
Interactive feedback
It contains various bullet frames , Such as message prompt box 、 Load box 、 Confirmation box 、 Pop up the operation frame at the bottom
Official documents : uni.showToast(OBJECT) | uni-app Official website
Message box
uni.showToast({
title: " You have no authority to ",
duration: 2000,
icon: "none",
});loding Load box
Be careful : Show loading Prompt box , It is necessary to call uni.hideLoading To close the prompt box .
uni.showLoading({
title: ' Loading '
}); // Load prompt box
setTimeout(function () {
uni.hideLoading(); // Close the loading prompt box
}, 2000);Message pop-up confirmation box
Show modal pop ups , There can be only one OK button , You can also have both OK and Cancel buttons . Similar to a API Integrated html in :alert、confirm
uni.showModal({
title: ' Tips ',
content: ' This is a modal pop-up window ',
success: function (res) {
if (res.confirm) {
console.log(' The user clicks ok ');
} else if (res.cancel) {
console.log(' The user clicks cancel ');
}
}
});Pop up the operation box at the bottom
Pop up the operation menu from the bottom
uni.showActionSheet({
itemList: ['A', 'B', 'C'],
success: function (res) {
console.log(' I've chosen No ' + (res.tapIndex + 1) + ' Button ');
},
fail: function (res) {
console.log(res.errMsg);
}
});Network request encapsulation
The first way
stay
srcCreate one in the directoryutilsFolder , It's good to create itrequest.jsstay
request.jsIn file , Write the code that encapsulates the network requestconst BASEURL = 'https://www.uinav.com/api/public/v1/' // const BASEURL = 'https://api-hmugo-web.itheima.net/api/public/v1/' const request = ({ url, method = 'GET', data = {}, header = {}, tip = ' Desperately loading ...' }) => { return new Promise((resolve, reject) => { uni.showLoading({ title: tip }) uni.request({ url: `${BASEURL}${url}`, method, data, header, success: res => { resolve(res.data) }, fail: err => { reject(err) }, complete: () => { uni.hideLoading() } }) }) } uni.$request = requeststay
main.jsTo introduceimport Vue from 'vue' import App from './App' import '@/utils/request'
4. Page usage
async fun2(){
let data = {}; // Request parameters
let res = uni.$request({
url:"xxx/xxxx",// Request path
method:"POST", // Request mode
header:{}, // Request header , If there is no change, don't write
data, // Parameters to be carried by the request
})
if(res.code == 0){
console.log(' The request is successful ')
}
}The second way :
1. Create... Under the root directory .env.development and .env.production file
env.development: development environment
ENV = 'development'
# Development base address
# VUE_APP_BASE_API = 'http://xxxxxxx.com/s2b2b/'
VUE_APP_BASE_API = '/s2b2b'
# Upload base address
# VUE_APP_BASE_API_upload = 'http://xxxxxx.com/api/'
VUE_APP_BASE_API_upload = '/api'
# Base address of external interface
# VUE_APP_BASE_API_open = 'http://xxxxxxxxx/api-open/s2b2b/'
VUE_APP_BASE_API_open = '/api-open'
# Set the port number
port = 8888.env.production : Production environment
ENV = 'production '
# Development base address
# VUE_APP_BASE_API = 'http://xxxxxxx.com/s2b2b/'
VUE_APP_BASE_API = '/s2b2b'
# Upload base address
# VUE_APP_BASE_API_upload = 'http://xxxxxx.com/api/'
VUE_APP_BASE_API_upload = '/api'
# Base address of external interface
# VUE_APP_BASE_API_open = 'http://xxxxxxxxx/api-open/s2b2b/'
VUE_APP_BASE_API_open = '/api-open'
2. stay src Create one in the directory utils Folder , It's good to create it request.js
3. stay request.js In file , Write the code that encapsulates the network request
// Network encapsulation
const BASEURL = process.env.VUE_APP_BASE_API
const request = ({
url,
method = 'GET',
data = {},
header = { // header The content depends on the project
// "content-type": "application/x-www-form-urlencoded",
// token: uni.getStorageSync("token"),
},
tip = ' Desperately loading ...'
}) => {
return new Promise((resolve, reject) => {
uni.showLoading({
title: tip
})
uni.request({
url: `${BASEURL}${url}`, // Request path
method, // Request mode
data, // Request parameters
header, // Request header
success: res => {
resolve(res.data.obj) // Request the results , It is recommended to print res to glance at
},
fail: err => {
reject(err)
},
complete: () => {
uni.hideLoading()
}
})
})
}
export default request4. stay src Create one in the directory api Folder , It's good to create it index.js
5. stay index.js In file , Write the code that encapsulates the interface request
import request from '@/utils/request.js'
// Login interface
export function loGinApi(data){
return request({
url:'xxxx', // Request path
method:"POST", // Request mode
header:{}, // Request header , If there is no change, don't write , According to individual projects
data // Request parameters
})
}6. Import and use in the page
import { loGinApi } from ' route '
// stay methods Send request in
methods{
async addClick(){
let data = {};
let res = await loGinApi(data)
if(res.code == 0){
console.log(' The request is successful ')
}
}
}
There are advantages and disadvantages in the two ways , Choose... For yourself , Or learn others' packaging methods from Baidu . I personally use the second method
Run as H5 when , Set up proxy Agents solve cross domain problems
1. stay manifest.json Set proxy in file

2. stay .env.development Change the base address
H5 You need to set the proxy , Therefore, the base address of wechat applet does not need to be changed 
3. It is also necessary to distinguish and judge in the network encapsulated files , It is judged that the current wechat applet environment , still H5 In the environment

Conditional compilation
Conditional compilation is marked with special comments , Based on these special comments at compile time , Compile the code in the comments to different platforms .
Official documentation : Cross terminal compatibility | uni-app Official website
Because I used cross end compatible conditional compilation , The official website has explained in detail , Don't go into details , It is recommended to check the document by yourself , Only basic usage is explained here
When we need to run a set of code on multiple terminals , for example , It needs to be compiled into H5 and Wechat applet , Some of our code needs to be compatible , At this time, you can use conditional compilation
** How to write it :** With #ifdef or #ifndef Add %PLATFORM% start , With #endif ending .
- #ifdef:if defined Only on a platform
- #ifndef:if not defined Except for a platform
- %PLATFORM%: Platform name
API Conditional compilation of
// #ifdef %PLATFORM%
Platform specific API Realization
// #endifConditional compilation of components
<!-- #ifdef %PLATFORM% -->
Platform specific components
<!-- #endif -->Conditional compilation of styles
/* #ifdef %PLATFORM% */
Platform specific style
/* #endif */%PLATFORM% The values are as follows :
| value | Conditions of entry into force |
|---|---|
| VUE3 | HBuilderX 3.2.0+ details (opens new window) |
| APP-PLUS | App |
| APP-PLUS-NVUE or APP-NVUE | App nvue |
| H5 | H5 |
| MP-WEIXIN | Wechat applet |
| MP-ALIPAY | Alipay applet |
| MP-BAIDU | Baidu applet |
| MP-TOUTIAO | Bytedance applet |
| MP-LARK | Flying Book applet |
| MP-QQ | QQ Applet |
| MP-KUAISHOU | Kwai Mini program |
| MP-JD | Jingdong applet |
| MP-360 | 360 Applet |
| MP | Wechat applet / Alipay applet / Baidu applet / Bytedance applet / Flying Book applet /QQ Applet /360 Applet |
| QUICKAPP-WEBVIEW | Quick application universal ( Including alliances 、 Huawei ) |
| QUICKAPP-WEBVIEW-UNION | Fast application Alliance |
| QUICKAPP-WEBVIEW-HUAWEI | Fast apply Huawei |
uni-UI
Official address : uni-app Official website
Plug-in address : uni-ui - DCloud Plug in market
uni-ui yes DCloud Provide a cross-border ui library , It is based on vue Component's 、flex Layout 、 nothing dom Span the full end of the ui frame .
Install and use
uni-ui There are multiple installation methods , It can be decided according to its own project
Official address :uni-app Official website
If you are using npm install , The following points need to be noted
1. cli By default, the project does not compile node_modules Of components under , Cause the failure of conditional compilation and other functions , Cause component exception You need to create... In the root directory vue.config.js file , increase @dcloudio/uni-ui The compilation of the package is normal
// vue.config.js
module.exports = {
transpileDependencies:['@dcloudio/uni-ui']
}2. sass edition , If node Version less than 16 ,sass-loader Please use less than @11.0.0 Version of ,[email protected] I won't support it [email protected] (opens new window) If node The version is greater than 16 , sass-loader It is recommended to use v8.x edition
uni Use charts in
Open the plugin address shared at the top , Search charts

You can search various chart components
If it's the first contact uni Developing diagrams , Pay attention to development efficiency , Recommend a fool chart : Autumn cloud ucharts echarts High performance cross end charting component - DCloud Plug in market
Be careful : This chart plug-in requires registered members to use online tools
ucharts Document address :uCharts Official website - Autumn cloud uCharts Cross platform chart library
边栏推荐
- A simple SQL injection shooting range exercise
- Literature learning (part101) -- converge clustering
- 公寓报修系统(IDEA,SSM,MySQL)
- 【5G NR】UE注册拒绝原因
- Hotel room management system based on jsp+servlet+mysql
- RTOS系列(13):汇编LDR指令、LDR伪指令、[Rn]寄存器间接引用 详细解析
- Message Oriented Middleware
- Common commands of raspberry pie
- Hash table questions (Part 1)
- Pricing is arbitrary, products are difficult to distinguish between true and false, and platforms are running away. Will the Tibetan market continue to be popular?
猜你喜欢

【着色器实现Shadow投影效果_Shader效果第八篇】

第3章业务功能开发(实现全选按钮实时的响应)
![RTOS series (13): assembly LDR instruction, LDR pseudo instruction, [rn] register indirect reference detailed analysis](/img/87/d116e729c771fcf3ce95958a45d85f.png)
RTOS series (13): assembly LDR instruction, LDR pseudo instruction, [rn] register indirect reference detailed analysis

Online bookstore system based on jsp+servlet+mysql

How to create a simple electron desktop program

Chapter 3 business function development (realize the real-time response of the select all button)

Huawei device remote login (Telnet, SSH) configuration

node+js搭建时间服务器

Pricing is arbitrary, products are difficult to distinguish between true and false, and platforms are running away. Will the Tibetan market continue to be popular?

Svg creative underline style JS special effect
随机推荐
mysql 如何获取两个集合的交集/差集/并集
CM4 development cross compilation tool chain production
A powerful port scanning tool (nmap)
Svg creative underline style JS special effect
记录两次多端排查问题的过程
@Autowired注解的原理
C#入门系列(三十) -- 异常处理
ip命令使用详解
R language error
Brush the title "sword finger offer" day01
Implementation of depth first and breadth first traversal of binary tree
Learn when playing No 5 | human high quality examination, right here →
Raspberry pie uses the command line to configure WiFi connections
RTOS系列(13):汇编LDR指令、LDR伪指令、[Rn]寄存器间接引用 详细解析
Hotel room management system based on jsp+servlet+mysql
刷题《剑指Offer》day01
Redis best practices
Advanced C language (XII) - dynamic memory management
【黑马程序员】Redis学习笔记003:Redis事务
Rk3399 development board i2c4 attaching EEPROM instance