catalogs
I. Introduction
II. Environment building (hello world)
2.1 Download HBuilderX
2.2 Download WeChat Developer Tools
2.3 Creating a uniapp project
2.4 Running in a browser
2.5 Running in WeChat Developer Tools
2.6 Running on a cell phone
III. Basic catalog structure of the project
IV. Overview of development norms
V. Global profiles ()
5.1 globalStyle
Navigation bar: background color, title color, title text
Navigation bar: enable drop-down refresh, drop-down background, drop-down style
5.2 pages
5.3 tabBar
5.4 condition (development start-up mode)
VI. Creating new pages and page configuration
VII. Configuring the tabBar
7.1 Basic Setup
7.2 Personalization
VIII. Components
8.1 text
8.2 icon
icon
Font Icons
IX. Page Style and Layout
9.1 Units of dimensions
9.2 Style Import
9.3 Selectors
9.4 Global and local styles
9.5 Using sass
X. Vue basic syntax review
xi. life cycle of uniapp
Application Life Cycle
Page Lifecycle
XII. Dropdown Refresh
XIII. Pull-up loading
XIV. Network requests
14.1 (OBJECT)
14.2 Secondary Encapsulation Request Object
XV. Data caching
15.1 (OBJECT)
15.2 (OBJECT)
15.3 (OBJECT)
15.4 (KEY,DATA)
15.5 (KEY)
15.6 (KEY)
XVI. Uploading and previewing pictures
16.1 Uploading
I. Introduction
If you are new to small programs, or if you have just heard the term, you may be like me before, with many doubts. For example:
What is uniapp and what are the similarities and differences between it and native WeChat apps?
Why do you recommend uniapp development?
It may still be cloudy after explaining it in a sentence or two here. My suggestion is to check out the following video, which I personally think is very clear and understandable.
Development of WeChat small program using native development or uniapp development, detailed introduction to the advantages and disadvantages of the native small program and uni-app development_beili_bilibili
----------------------------------------------------------------------------------------------------------------------
ps: The moving images in the blog may have residual shadows when switching, they are not real, so please be careful to recognize them.
If it's helpful to you, give a like 👍 for the hard work, it doesn't cost anything anyway~😁
----------------------------------------------------------------------------------------------------------------------
II. Environment building (hello world)
2.1 Download HBuilderX
HBuilderX-Efficient Geek Tips
Of course you can choose another IDE, but the official website recommends HBuilderX for natural uniapp integration.
2.2 Download WeChat Developer Tools
We want to finally pack into the WeChat small program must be in the WeChat developer tools to preview, then need to download the WeChat developer tools.
WeChat Developer Tools Download Address and Update Log | WeChat Open Documentation
2.3 Creating a uniapp project
Once HBuilderX is downloaded, just double-click and run the file, it is installation free.
Then we create a new uniapp project and just follow the picture below.
It will then generate the basic structure of the project by default.
2.4 Running in a browser
Then the first time you run it, the console will prompt to automatically go and download the relevant plugin, which will require you to re-run it again once it's done.
2.5 Running in WeChat Developer Tools
Then I started it up to test it and found that it failed. After checking the two items it reported as errors, there's nothing wrong with them either.
Then the problem may be with the microsoft developer, we need to go into theWeChat Developer Tools->Settings->Security, and then turn on the port number of the service.
Then just re-run it.
2.6 Running on a cell phone
Same for Android and ios, but you need to connect it on with a data cable.
The operation is similar, interested can go to try, here no longer demonstrated. However, it should be noted that the ios end is a little bit of trouble, it seems that now does not support the direct run.
III. Basic catalog structure of the project
IV. Overview of development norms
In order to achieve multi-end compatibility, taking into account factors such as compilation speed and runtime performance, uni-app has agreed on the following development specifications:
-
Page files follow the Vue single-file component specification
-
Component labels are close to the applet specification, see uni-app component specification for details
-
The interface capability (js api) is close to the WeChat applet specification, but the prefix wx needs to be replaced with uni, see the uni-app interface specification for details
-
Data binding and event handling are standardized, complementing the lifecycle of apps and pages.
-
In order to be compatible with multi-terminal operation, it is recommended to use flex layout for development
V. Global profiles ()
file is used to configure the uni-app globally, determining the path to the page file, the window style, the native navigation bar, the native tabbar at the bottom, and so on.
5.1 globalStyle
Used to set the status bar, navigation bar, title, window background color, etc. of the application.
ps: the following I have only listed what I personally think are the more common attributes, if there is a need to strongly recommended to go to the official website to see, the most complete.
Navigation bar: background color, title color, title text
causality | typology | default value | descriptive | Description of platform differences |
---|---|---|---|---|
navigationBarBackgroundColor | HexColor | #F8F8F8 | Navigation bar background color (same as status bar background color) | APP and H5 are #F8F8F8, please refer to the corresponding small program documentation for small program platforms |
navigationBarTextStyle | String | black | Navigation bar title color and status bar foreground colorThe only support is for theblack/white | Alipay applet is not supported, please use |
navigationBarTitleText | String | Navigation bar title text content | ||
navigationStyle | String | default | Navigation bar style, only support default/custom. custom is to cancel the default native navigation bar, need to see theNotes on use | WeChat Small Program 7.0+, Baidu Small Program, H5, App (2.0.3+) |
demonstrations
Note: If you didn't modify it completely successfully, or none of the changes take effect, it may be caused by setting the configuration style of the page, which will override the style of the same property in the global style configuration. This is because the page configuration has higher priority than the global configuration. We can just delete the page configuration style.
Navigation bar: enable drop-down refresh, drop-down background, drop-down style
causality | typology | default value | descriptive | Description of platform differences |
---|---|---|---|---|
backgroundColor | HexColor | #ffffff | The background color of the window shown in the dropdown | WeChat small program |
backgroundTextStyle | String | dark | Styles for dropdown loading, only dark / light are supported. | WeChat small program |
enablePullDownRefresh | Boolean | false | Whether to enable dropdown refreshFor details, seePage Lifecycle。 | |
onReachBottomDistance | Number | 50 | The distance from the bottom of the page when the page pull-up bottom-touch event is triggered, only px is supported.Page Lifecycle |
demonstrations
5.2 pages
uni-app
Configure what pages the application consists of with the pages node, which receives an array of items, each of which is an object with the following property values:
causality | typology | default value | descriptive |
---|---|---|---|
path | String | Configure the page path | |
style | Object | Configuration page window performance, configuration items refer to the followingpageStyle |
Tips:
- The first item in the pages node is the application entry page(i.e. home page)
- Adding/removing pages in the applicationThe pages array will need to be modified in any case.
- filenameNo need to write a suffixThe framework will automatically find the page resources under the path
For example, it is generated by default when the project is created:
If it's not clear, I'll demonstrate its use in Chapter 6, Creating New Pages and Configuring Pages.
5.3 tabBar
If the application is a multi-tab application, you can specify the first level of navigation bar and the corresponding page to be displayed when switching tabs through the tabBar configuration item.
Please see Chapter VII for details!
5.4 condition (development start-up mode)
Startup mode configuration, effective only during development, used to simulate a direct-to-page scenario, e.g., the page that opens when the user clicks on it after the applet is forwarded.
Property Description:
causality | typology | Required or not | descriptive |
---|---|---|---|
current | Number | be | Currently active mode, index value of list node |
list | Array | be | List of startup modes |
list description:
causality | typology | Required or not | descriptive |
---|---|---|---|
name | String | be | Startup mode name |
path | String | be | Startup Page Path |
query | String | clogged | The startup parameters, which can be found in the page'sonLoad function to get the |
Attention: Running it on the real machine in the App opens the configured page directly, but you need to change the compilation mode manually in the WeChat developer tool.
demonstrations
Create another test page to test it
Configure the condition condition:
VI. Creating new pages and page configuration
You can create a new page directly, or you can create a directory and then a file.
Then go to the file and set the page path and also configure the page style.
Done, let's take a look at it by opening it in a browser and typing in that path to see the page we just created.
And it was found to successfully override the globally styled navigation bar title text.
Seven,Configuring the tabBar
7.1 Basic Setup
Tips
- When setting theWhen position is topwillNo icon will be displayed
- tabBar in thelist anarraysThe only way to configureMinimum 2、Up to 5 tab, tab Sort the array in order.
- tabbar toggles may not render in time the first time they load, you can pop up a waiting snowflake in the onLoad lifecycle of each tabbar page (hello uni-app uses this approach)
- Once a tabbar page has been shown once, it remains in memory. Switching tabbar pages again will only trigger onShow for each page, not onLoad.
- The tabbar at the top is currently only supported on WeChat apps... If you need to use the top tab.not recommendedInstead of using the tabbar's top setting, thedo it oneselfTop tab, see hello uni-app-> templates-> top tab.
causality | typology | mandatory field | default value | descriptive | Description of platform differences |
---|---|---|---|---|---|
color | HexColor | be | Default text color on tab | ||
selectedColor | HexColor | be | Text on tabdecide upon a candidatecurrent color | ||
backgroundColor | HexColor | be | tab's background color | ||
borderStyle | String | clogged | black | The color of the upper border of the tabbar, black/white, other colors are also supported. | App 2.3.4+ 、H5 3.0.0+ |
list | Array | be | A list of tabs, see the description of the list attribute, with a minimum of 2 and a maximum of 5 tabs. | ||
position | String | clogged | bottom | Optional values bottom, top | The top value is only supported by WeChat Small Program |
The list property has the following attribute values
causality | typology | mandatory field | clarification | Platform differences |
---|---|---|---|---|
pagePath | String | be | The path to the page must be defined in pages first | |
text | String | be | Button text on the tab is not required on App and H5 platforms. For example, you can put a + icon in the center with no text. | |
iconPath | String | clogged | Image path, icon size limit is 40kb, recommended size is 81px * 81px, this parameter is invalid when the position is top, does not support network images, does not support font icons | |
selectedIconPath | String | clogged | The path of the image when it is selected, the size of the icon is limited to 40kb, the recommended size is 81px * 81px, this parameter is invalid when the position is top. |
demonstrations
7.2 Personalization
We see a lot of small programs that have a lot of its bottom navigation bar which has a middle icon protruding from it, such as this:
How does it do that?
In fact, it is also a configuration item inside the tabbar, midButton property, and list property rating can be.
causality | typology | mandatory field | default value | descriptive | Description of platform differences | |
---|---|---|---|---|---|---|
midButton | Object | clogged | Middle Button Only available when there are an even number of list items. | App 2.3.4+、H5 3.0.0+ |
Description of the midButton property
causality | typology | mandatory field | default value | descriptive |
---|---|---|---|---|
width | String | clogged | 80px | The width of the center button, tabBar Other items are divided equally after subtracting this width, the default value is divided equally with other items. |
height | String | clogged | 50px | The height of the center button can be greater than the height of the tabBar to achieve the effect of a raised center. |
text | String | clogged | Text for the center button | |
iconPath | String | clogged | Image path of the center button | |
iconWidth | String | clogged | 24px | Image width (height scaled equally) |
backgroundImage | String | clogged | Path to the background image of the center button | |
iconfont | Object | clogged | font icon, priority over iconPath |
The specific code is as follows:
It has a feature that only supports apps and H5 at the moment, which means that small programs and these cannot be displayed.
And midButton does not have a pagePath, you need to listen to the click event, and handle the logic of the clicked behavior by yourself.
Check the official website for details: Page routing | uni-app official website
What if we want to have this feature on the applet side as well? You can actually customize the tabbar to hide the native tabbar.
Specific implementation here will not write, slightly more complex. Interested in the back of their own search for related methods. The official website also has a relevant introduction: Page routing | uni-app official website
Of course you can also go to the uniapp plugin market to search for people to get the plugin, this is a little more simple, follow the requirements of the step-by-step adjustment can be.
I will also add how to customize the settings of the tabbar when I have time in the future.
VIII. Components
- Components are the basic building blocks of the view layer.
- A component is a package of separate and reusable functional modules.
To put it bluntly, it is the label. uniapp can use the default label provided by html, uniapp also encapsulates some components can be used.
8.1 text
Text component. Used to wrap text content.
Attribute Description
property name | typology | default value | clarification | Description of platform differences |
---|---|---|---|---|
selectable | Boolean | false | Whether the text is optional | |
user-select | Boolean | false | Whether the text is optional | WeChat small program |
space | String | Show Consecutive Spaces | Pinned applets are not supported | |
decode | Boolean | false | Decode or not | Baidu, nail small program does not support |
space value description
(be) worth | clarification |
---|---|
ensp | Chinese character space half size |
emsp | Chinese character space size |
nbsp | Space size according to font setting |
8.2 icon
icon
icon (computing)
Attribute Description
property name | typology | default value | clarification |
---|---|---|---|
type | String | Type of icon | |
size | Number | 23 | Size of the icon in px |
color | Color | The color of the icon is the same as the color of the css. |
Description of valid values for each platform type:
flat-roofed building | type Valid values |
---|---|
App, H5, WeChat small program, QQ small program | success, success_no_circle, info, warn, waiting, cancel, download, search, clear |
Alipay applet | info, warn, waiting, cancel, download, search, clear, success, success_no_circle,loading |
Baidu applet | success, info, warn, waiting, success_no_circle, clear, search, personal, setting, top, close, cancel, download, checkboxSelected, radioSelected, radioUnselect |
demonstrations
Since the icon component behaves differently from one end to the other, it can be used to create a new icon by using theFont Icons way to make up for the differences at each end of the spectrum.
Font Icons
Also, these are the icons provided by uniapp by default, so if you wish to use personalized icons, then you can use font icons.
uniapp supports the use of font icons in the same way as a normal web project, with the following caveats:
- Support for base64 format font icons.
- Support for network path font icons.
- The applet does not support the use of local files in css, including local background images and fonts. It needs to be base64.
- Network paths must be prefixed with protocol headers
https
。 - through (a gap) The code copied above has no protocol header by default.
- through (a gap) The fonts downloaded from nvue are all of the same name (the fonts are all called iconfont, as you can see when installing the fonts), when using them in nvue you need to pay attention to the fact that duplicates of these fonts may not be displayed correctly, and you can use a tool to modify them.
- Use of local path icon fonts requires attention:
- For the convenience of developers, when the font file is less than 40kb, the
uni-app
It is automatically converted to base64 format; - Fonts larger than or equal to 40kb may have performance problems if they are still converted to base64, if developers must use them, they need to convert them to base64 format themselves, or move them to a server and reference them from a network address;
- The recommended reference path for font files is ~@ The absolute path at the beginning.
- For the convenience of developers, when the font file is less than 40kb, the
Without further ado, let's get right to the demo
Copy everything except the html page into the project and follow the steps below:
ok, so even if the configuration is complete, we can use it in the page.
Then we open the html page in the downloaded file, find the font style corresponding to the icon and use it, remove the preceding. NO.
The color, size, etc. of the font icon can also be changed through css styles.
concern
Sometimes you will find that you follow my steps exactly, the results can be used in the browser, but the use of small programs can not be displayed, and the console also reported an error. This time either a different kind of resource, or go to adjust the use of https beginning of the network resources. Specific problem specific solution will be fine.
IX. Page Style and Layout
The uni-app css is basically the same as the web css.
The uni-app has vue pages and nvue pages. vue pages are rendered by webview, nvue pages on the app side are rendered natively. Styles in nvue pages are more limited than in the web.
This article focuses on styling considerations for vue pages.
9.1 Units of dimensions
uni-app
Generic css units supported includepx、rpx。
rpxi.e., responsive px, a dynamic unit that adapts itself to the width of the screen, based on a 750-wide item.750rpx is exactly the width of the screen,As the screen gets wider, the actual rpx display will be scaled up proportionally.。
9.2 Style Import
utilization@import
The statement can beImporting Outreach Style Sheets,@import
of the outreach stylesheet that needs to be imported.relative pathuse;
Indicates the end of the statement.
9.3 Selectors
The currently supported selectors are:
picker | example | sample description |
---|---|---|
.class | .intro | Select all components that have class="intro". |
#id | #firstname | Select the components that have |
element | view | Select all view components |
element, element | view, checkbox | Select the view component of all documents and all checkbox components. |
::after | view::after | Inserts content behind the view component.Only works on vue pages |
::before | view::before | Inserts content in front of the view component.Only works on vue pages |
Attention:
-
exist
uni-app
You can't use the*
Selector. -
Only class selectors are supported in WeChat applet custom components
-
page
equivalent tobody
nodes, for example:
<! -- Sets the background color of the page, using scoped will cause it to fail -- >
page {
background-color: #ccc;
}
9.4 Global and local styles
Defined in The style in theGlobal Stylethat acts on every page. In thevue file in the pages directoryThe style defined inLocal Stylewhich works only on the corresponding page and overrides the same selector in the
Attention:
- hit the nail on the head
@import
statements can import outreach styles that work just as well on every page. - Global styles are not supported on nvue pages.
9.5 Using sass
We can see in the root directory of the project auni-scss
Documentation.
uni-scss
beuni-ui
A set of global styles is provided by a few simple class names and thesass
variables for simple page layout operations such as colors, margins, rounded corners, and so on.
So how do you use sass?
First install the sass plugin
To use, remember to add the attribute lang="scss" to the style tag.
X. Vue basic syntax review
uniapp is a framework based on vue for packaging. So in order to use it well, you have to know vue. if you know vue, then you can skip here, if you don't, then I will briefly learn it with you.
Getting event objects
If the method in v-on: is not passed parameters, then by default it gets the event object
Just upload a formal parameter in the method.
xi. life cycle of uniapp
Application Life Cycle
/ | uni-app official website
The concept of the life cycle
The entire process of creating, running, and destroying an object.
lifecycle function
Each stage in the life cycle is accompanied by the triggering of functions, which are called life cycle functions.
uni-app
The following application lifecycle functions are supported
function name | clarification |
---|---|
onLauch | Triggered when uni-app initialization is complete (only triggered once globally) |
onShow | When the uni-app starts, or goes from the background to the foreground to display the |
onHide | When the uni-app goes from the frontend to the backend |
onError | Triggered when the uni-app reports an error. |
Page Lifecycle
Page Introduction | uni-app official website
uni-app
The following page life cycle functions are supported:
function name | clarification | Description of platform differences | minimum version |
---|---|---|---|
onInit | Listen to the initialization of the page, its parameters are the same as the onLoad parameter, for the data passed in the previous page, the parameter type is Object (used for page passing), the trigger time is earlier than onLoad. | Baidu applet | 3.1.0+ |
onLoad | Listen to the page load, its parameter is the data passed by the previous page, the parameter type is Object (used for page passing), refer to thetypical example | ||
onShow | Listens for page displays. Triggered every time a page appears on the screen, including returning from a lower page point to reveal the current page. | ||
onReady | Listens for the initial rendering of the page to complete. Note that if the rendering is fast, it will be triggered before the page entry animation completes | ||
onHide | Listening for page hides | ||
onUnload | Listen for page unloading | ||
onResize | Listen for window size changes | App, WeChat applet, Shutterbug applet | |
onPullDownRefresh | Listen to the user's dropdown action, generally used for dropdown refresh, refer to thetypical example | ||
onReachBottom | The event that scrolls the page to the bottom (not scroll-view to the bottom), often used to pull down the next page of data. See the notes below | ||
onTabItemTap | Triggered when tab is clicked, parameter is Object, see notes below | WeChat small program, QQ small program, Alipay small program, Baidu small program, H5, App, Quick Hand small program, Jingdong small program |
We minimize the page and open the
We switch from tabBar and it's the same thing.
XII. Dropdown Refresh
One way of refreshing the dropdown, as mentioned earlier, is through global configuration.
But we don't recommend it, we want that page to be turned on if it's needed and not turned on if it's not needed.
We want the dropdown to refresh and trigger some events.
It is only necessary to pass the onPullDownRefresh function. It's listed in the previous page's lifecycle functions.
Once the refresh is complete, we can close it with the (); close the
XIII. Pull-up loading
We notice that it starts saying bottoming out before it has bottomed out, this is because there is a default bottoming out distance . We can set the default bottoming distance
Then just come back and test it. No demo here.
After bottoming out, we can load him with the next page of data.
XIV. Network requests
(OBJECT) | uni-app official website
14.1 (OBJECT)
Initiate a web request.
When running on each applet platform, network-related APIs need to be configured with a domain whitelist before use.
OBJECT Parameter Description
parameter name | typology | mandatory field | default value | clarification | Description of platform differences |
---|---|---|---|---|---|
url | String | be | Developer Server Interface Address | ||
data | Object/String/ArrayBuffer | clogged | Parameters of the request | The ArrayBuffer type is not supported below App 3.3.7. | |
header | Object | clogged | Set the header of the request, no Referer can be set in the header. | App, H5 will automatically bring cookies, and H5 can not be manually modified! | |
method | String | clogged | GET | See note below for valid values | |
timeout | Number | clogged | 60000 | Timeout time in ms | H5 (HBuilderX 2.9.9+), APP (HBuilderX 2.9.9+), WeChat applet (2.10.0), Alipay applet |
dataType | String | clogged | json | If set to json, it will attempt to do a | |
responseType | String | clogged | text | Sets the data type of the response. Legal values: text, arraybuffer | Alipay applet is not supported |
sslVerify | Boolean | clogged | true | Verify ssl certificate | App Android support only (HBuilderX 2.3.3+), does not support offline packaging |
withCredentials | Boolean | clogged | false | Whether or not to carry credentials (cookies) for cross-domain requests | H5 support only (HBuilderX 2.6.15+) |
firstIpv4 | Boolean | clogged | false | Prioritize ipv4 for DNS resolution | App-Android support only (HBuilderX 2.8.0+) |
enableHttp2 | Boolean | clogged | false | Enable http2 | WeChat small program |
enableQuic | Boolean | clogged | false | Open quic | WeChat small program |
enableCache | Boolean | clogged | false | Enable cache | WeChat Small Program, ByteDance Small Program 2.31.0+ |
enableHttpDNS | Boolean | clogged | false | Whether to enable HttpDNS service. If so, you need to enter the httpDNSServiceId as well. For more information on how to use HttpDNS, please refer to theMobile Resolution HttpDNS | WeChat small program |
httpDNSServiceId | String | clogged | HttpDNS Service Provider Id. See HttpDNS Usage for details.Mobile Resolution HttpDNS | WeChat small program | |
enableChunked | Boolean | clogged | false | opens transfer-encoding chunked | WeChat small program |
forceCellularNetwork | Boolean | clogged | false | Sending requests using mobile network under wifi | WeChat small program |
enableCookie | Boolean | clogged | false | Edit cookie in headers when turned on | Alipay applet 10.2.33+ |
cloudCache | Object/Boolean | clogged | false | Whether to enable cloud acceleration (seeCloud Acceleration Services) | Baidu applet 3.310.11+ |
defer | Boolean | clogged | false | Controls whether the current request is delayed until the first screen is rendered. | Baidu applet 3.310.11+ |
success | Function | clogged | Callback function that receives a successful return from the developer server | ||
fail | Function | clogged | Callback Functions for Failed Interface Calls | ||
complete | Function | clogged | Callback function for the end of the interface call (executed on both success and failure of the call) |
method Valid values
Note: The valid value of method must be capitalized, each platform supports different valid values of method, see the following table for details.
method | App | H5 | WeChat small program | Alipay applet | Baidu applet | Byte Jump applet, Flying Book applet | Snapdragon applet | Jingdong Small Program |
---|---|---|---|---|---|---|---|---|
GET | √ | √ | √ | √ | √ | √ | √ | √ |
POST | √ | √ | √ | √ | √ | √ | √ | √ |
PUT | √ | √ | √ | x | √ | √ | x | x |
DELETE | √ | √ | √ | x | √ | x | x | x |
CONNECT | x | √ | √ | x | x | x | x | x |
HEAD | √ | √ | √ | x | √ | x | x | x |
OPTIONS | √ | √ | √ | x | √ | x | x | x |
TRACE | x | √ | √ | x | x | x | x | x |
success Description of return parameters
parameters | typology | clarification |
---|---|---|
data | Object/String/ArrayBuffer | Data returned by the developer server |
statusCode | Number | HTTP status code returned by the developer server |
header | Object | HTTP Response Header returned by the developer server |
cookies | Array.<string> |
Cookies returned by the developer server, formatted as an array of strings |
data Data description
The final data sent to the server is of type String, if the incoming data is not of type String, it will be converted to String. the conversion rules are as follows:
-
insofar as
GET
method, which converts the data to a query string. e.g.{ name: 'name', age: 18 }
The result of the conversion isname=name&age=18
。 -
insofar as
POST
method andheader['content-type']
because ofapplication/json
The data is serialized in JSON. -
insofar as
POST
method andheader['content-type']
because ofapplication/x-www-form-urlencoded
will convert the data to a query string.
beta (software)
We'll start by getting a test interface with springboot.
The interface is fine, and then we try
Okay, it's done.
One problem we found is that the internal operation mechanism of the applet is different from the web page, the code in the applet does not run in the browser, because there is no restriction on cross-domain requests for data in applet development.
So we can access it without doing cross-domain processing.
concern
If in WeChat Developer Tools, it is not sent successfully, you can try the following method.
14.2 Secondary Encapsulation Request Object
It seems a bit cumbersome if I have to go and write the ip address port number of the request for each call like above.
Let's say the ip address or port number changes, it's horrible to have to change it one by one for every request!
Therefore, we need to unify the secondary packaging to set or modify these public parameters in a unified way. Reduce redundancy and improve efficiency.
const BASE_URL = 'http://localhost:8000'
export const myRequest = (options) => {
return new Promise((resove,reject)=>{
({
url: BASE_URL + ,
method: || 'GET',
data: || {},
success: (res) => {
if( != 1){
return ({
title:'Failed to get data'
})
}
resove(res)
},
fail: (err) => {
({
title:'Request Interface Failure'
}),
reject(err)
}
})
})
}
Testing: writing page-tuning interfaces
Let's try a different interface this time.
(Haha, I actually wrote that interface above at the beginning of the year and now I can't find the code to rewrite it myself 😂)
We try to close the interface and refresh the page again to find that the page says: Request for interface failed. ok, fully compliant.
Again, since our request is returned via Promise, we can call the method asynchronously. With a little modification, it can be successfully fetched as well. (Remember to restart the backend project 😆)
XV. Data caching
15.1 (OBJECT)
commander-in-chief (military)The data is stored in the key specified in the local cachemeetingOverwrite the contents of the original keyIt's aasynchronous interface。
OBJECT Parameter Description
parameter name | typology | mandatory field | clarification |
---|---|---|---|
key | String | be | The specified key in the local cache |
data | Any | be | Only native types and objects that can be serialized are supported. |
success | Function | clogged | Callback Functions for Successful Interface Calls |
fail | Function | clogged | Callback Functions for Failed Interface Calls |
complete | Function | clogged | Callback function for the end of the interface call (executed on both success and failure of the call) |
15.2 (OBJECT)
Asynchronous from local cacheGet the content corresponding to the specified key。
OBJECT Parameter Description
parameter name | typology | mandatory field | clarification |
---|---|---|---|
key | String | be | The specified key in the local cache |
success | Function | be | Callback function for interface calls, res = {data: content corresponding to key} |
fail | Function | clogged | Callback Functions for Failed Interface Calls |
complete | Function | clogged | Callback function for the end of the interface call (executed on both success and failure of the call) |
success Description of return parameters
parameters | typology | clarification |
---|---|---|
data | Any | Key Correspondence |
15.3 (OBJECT)
Removes the specified key from the local cache asynchronously.
OBJECT Parameter Description
parameter name | typology | mandatory field | clarification |
---|---|---|---|
key | String | be | The specified key in the local cache |
success | Function | be | Callback functions for interface calls |
fail | Function | clogged | Callback Functions for Failed Interface Calls |
complete | Function | clogged | Callback function for the end of the interface call (executed on both success and failure of the call) |
15.4 (KEY,DATA)
Storing data in a key specified in the local cache overwrites the contents of the original key, which is a synchronization interface.
15.5 (KEY)
Fetches the content corresponding to the specified key from the local cache synchronously.
15.6 (KEY)
Synchronizes the removal of the specified key from the local cache.
XVI. Uploading and previewing pictures
16.1 Uploading
(OBJECT)
Select a picture from a local album or take a picture using the camera.
If you need a richer camera API (e.g., calling the front camera directly), refer to the
WeChat applet from base library 2.21.0. Maintenance is stopped, please use the Substitute.
OBJECT Parameter Description
parameter name | typology | mandatory field | clarification | Description of platform differences |
---|---|---|---|---|
count | Number | clogged | Maximum number of images that can be selected, default 9 | See note below |
sizeType | Array<String> | clogged | original, compressed, both by default. | App, WeChat small program, Alipay small program, Baidu small program |
extension | Array<String> | clogged | Filter by file extensions, each of which cannot be an empty string. The default is not filtered. | H5(HBuilder X2.9.9+) |
sourceType | Array<String> | clogged | album selects images from an album, camera uses the camera, both are available by default. If you want to open the camera directly or select an album directly, please use only one option. | |
crop | Object | clogged | Image cropping parameter, sizeType is invalid after setting. | App 3.1.19+ |
success | Function | be | Success returns a list of local file paths for the image tempFilePaths | |
fail | Function | clogged | Callback Functions for Failed Interface Calls | Small programs, apps |
complete | Function | clogged | Callback function for the end of the interface call (executed on both success and failure of the call) |
Description of the crop parameter
parameter name | typology | mandatory field | clarification | Description of platform differences |
---|---|---|---|---|
quality | Number | clogged | The value range is 1-100, the smaller the value, the lower the quality (only valid for jpg format). The default value is 80. | |
width | Number | be | The width of the crop in px, used to calculate the crop aspect ratio. | |
height | Number | be | The height of the crop, in px, used to calculate the crop aspect ratio. | |
resize | Boolean | clogged | Whether or not to use width and height as the real pixel value of the cropped saved image. Default value is true. note: if set to false, the pixel value of the image will be shown in the crop edit screen, if set to true, it will not be shown. |
Tips
-
The count value's performance on the H5 platform is based on the browser's own specifications. The results of the current test show that it can only limit single/multiple choices, but not the number. Moreover, very few mobile browsers can support multi-select.
-
The sourceType value behaves differently on H5 platforms depending on the browser, and generally cannot be restricted to use only albums, and some browsers cannot restrict the use of the camera.
-
The user authorization API can be used to determine if the user has granted the app access to the photo album or camera(OBJECT) | uni-app official website
-
App side if you need to select non-media files, you can search in the plug-in marketplaceFile Selection, of which the Android side can be used without a native plugin, while the iOS side requires a native plugin.
-
Selecting photos mostly for uploading, uni ui encapsulates betteruni-file-picker component, file selection, uploading to uniCloud's free storage and cdn, one-stop integration. Highly recommended.
Note: The temporary path of the file can be used normally during the current startup of the application, and if you need to save it persistently, you need to call the, which will not be accessible until the next time the application is launched.
success Description of return parameters
parameters | typology | clarification |
---|---|---|
tempFilePaths | Array<String> | List of local file paths for images |
tempFiles | Array<Object>、Array<File> | A list of local files for the image, each item is a File object |
The File object has the following structure
parameters | typology | clarification |
---|---|---|
path | String | Local File Path |
size | Number | Local file size in B |
name | String | File names containing extensions, H5 support only |
type | String | File type, H5 support only |
OK, it's as simple as getting the image from local to display on the page. But the actual upload is not done yet.
Here I am going to call the backend interface to complete the upload process.
I'm too tired to write this for now.
If this blog is well received, I'll finish updating it as soon as possible , thanks for the encouragement~!