The project build
Use NPM init -y to initialize the NPM project, then install the NPM package you need using your preferred method (NPM, YARN); Non-h5 platform projects do not support packages that use DOM manipulation.
Use applets
Using the applets component needs to be configured in pages. Json and referenced in the specific page:
{"path":"pages/Home/index", "style": {"navigationBarTitleText": "Home ", "usingComponents": {"van-search": { "/wxcomponents/vant-weapp/search/index" } } }Copy the code
Use globally:
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8",
"usingComponents": {
"van-button": "/wxcomponents/vant-weapp/button/index",
"icon": "/wxcomponents/vant-weapp/icon/index",
"van-search": "/wxcomponents/vant-weapp/search/index"
}
},
Copy the code
Note that the referenced component name must be lowercase; otherwise, the component may not be found
Conditional compilation
Conditional compilation at the code level is implemented using a special comment syntax that starts with #ifdef or #ifndef plus %PLATFORM% and ends with #endif.
Need of special note is conditional compilation, whole directory project under the root directory to build platforms folder, and then according to the different platform to establish different folders (such as mobile phone client to create the app – plus folder), in the allocation of pages path will differ according to different loading platform of the page.
{" path ":" platforms/app - plus/researched researched ", "style" : {" navigationBarTitleText ":" voice recognition "}}Copy the code
The page configured above will only load on app-Plus related platforms.
Easycom Component mode HBuilder support EasyCOM component mode, generally use components we need to install, reference, register three steps. With easycom components, you can simply download components to the components directory and follow the components/ component name/component name. Vue directory structure, you can directly use components in the page, without importing, registering; Unused components are automatically removed when packaging.
Easycom also supports custom configurations, which can be found in the official documentation
Development item Configuration
As we develop, we can specify the launch page, which needs to be configured in pages. Json. We can configure multiple items, and then select them at run time.
"List ": [{"name": "Market", // Pattern name" path": [{"name": "Market", // pattern name" path": "Pages /Cart/index", // start the page, mandatory "query": "" // start parameters, in the page onLoad function}]Copy the code
Note: The query startup parameter is not available in the onLoad function as described in the documentation, and we will cover this problem and how to fix it later.
The environment variable
The built-in environment variable process.env.node_env can be used to determine the current operating environment, so that different ways can be used in different environments.
const isDev = process.env.NODE_ENV === 'development'
const http = axios.create({
baseURL: isDev ? DEV : PRO,
timeout: 3000
})
Copy the code
Development skills
Local image
Uni-app supports the use of local images, which can be imported directly into the image tag or used as background images. Local images are automatically converted to Base64 format on platforms that do not support local images (applets), but the image must be smaller than 40KB. Use image reference paths that start with ~@, otherwise you may not find resources in Windows.
When using the local image tag, the image will be stored in the packaged vendor.js file in base64 format, which will be referenced when the applet is loaded. If too many local images are used, the applet will run slowly for the first time. When used as a background image, the image is stored in the style file of the reference file, which increases the size of the package but has little impact on startup speed.
Large images are recommended to use network images, and small images should be used as background images instead of being referenced in the image tag.
Applets sharing
Applet sharing is triggered by clicking the button with open-type share or the share button of the page. The sharing content is the return value of the page onShareAppMessage, which includes title- share title, path- share path, imageUrl- share picture, OnShareAppMessage can only be defined on the page, not in the component.
If the information you share is dynamic, you can bind data via the data-binding button:
<button open-type="share"
:data-title="***"
:data-imgurl="***"
:data-path="***">
</button>
Copy the code
You can then get the data in the callback function:
onShareAppMessage(data) {
let dataset = data.target.dataset
return {
title: dataset.title,
imageUrl: dataset.imgurl,
path: dataset.path
}
},
Copy the code
The life cycle
In UNI-App, there are times when the life cycle can be unexpected and off-guard:
When sharing through applets, we usually bring routing parameters, and the uni-App startup option can also be configured with parameters. For normal route hops, we can get parameters from onLoad, but in the two scenarios we just mentioned, we cannot get parameters from onLoad, only from onLauch. If we need to get routing parameters, we can only get them in onLauch, save them in other ways (vuex or whatever), and get them where we need them.
The life cycle of the TAB page is different from that of other pages. Switching the TAB page does not trigger the onLoad event, but opening the general page will trigger the onLoad page.
When the back goes back to the previous page, it usually doesn’t fire onLoad, but it does fire onShow.
When selecting an image, opening the album and returning to the applet will trigger the applet’s onShow.
Uni. UploadFile: Uni. UploadFile: uni.
uni.chooseImage({ success: (chooseImageRes) => { const tempFilePaths = chooseImageRes.tempFilePaths; Uni. UploadFile ({url: 'https://www.example.com/upload', / / for the sample only, not real interface address filePath: tempFilePaths [0], name: 'file', formData: { 'user': 'test' }, success: (uploadFileRes) => { console.log(uploadFileRes.data); }}); }});Copy the code
If you are using a third party object storage OSS you can also use uni.uploadFile for direct upload:
Configure Bucket cross-domain access. When a client sends a form directly to the OSS, it sends a request message with Origin from the browser to the OSS. OSS validates cross-domain rules (CORS) for request messages with Origin headers. Therefore, cross-domain rules need to be set for buckets to support the Post method. On the OSS administration Console, modify rule configurations. Configure the extranet domain name to the applet domain name whitelist; In the ACCESS domain name area of the OSS Management Console, view the Bucket domain name, log in to the applets platform, and configure the whitelist for the uploaded applets. If this parameter is not configured, the development environment will not be affected, but the applets released (including the release experience version) cannot be uploaded. According to the requirements of the platform, generate the required information for uploading and upload using uni.uploadFile
import md5 from 'md5' export default ({ dir, host, expire, signature, policy, accessid }) => { return new Promise((resolve, reject) => { uni.chooseImage({ count: 1, success: (res) => { const filePath = res.tempFilePaths[0] const ext = filePath.replace(/([\S\s]+)\.(\S+)$/, '$2') const key = '${dir}/${md5(math.random ())}.${ext} '// filename md5 rename uni.uploadFile({url: host, filePath, name: uni) 'file', formData: { policy, OSSAccessKeyId: accessid, signature, expire, key, }, success: () = > {resolve (` ${host} / ${key} `)/picture/return address}, fail (err) {reject (err)}})}, fail (err) {reject (err)}})})}Copy the code
If using Ali Cloud can refer to this document – small program direct transmission practice
Small program top fit
In some cases, we need to customize the title bar, but the height of the title bar may be different in different models of mobile phones. Here, we can adjust the position of the capsule in the upper right corner of wechat mini program.
We can through the uni. GetMenuButtonBoundingClientRect () to obtain information about the capsule menuButton, menuButton contains capsule the location information of top, bottom, left, right, And capsule size information width, height; From this information we can calculate the appropriate title bar height.
rolling
Page-level scrolling is configured by the page style item in pages. Json with the following values:
Attribute Type Default Value Description disableScroll Boolean false If this parameter is set to true, the page cannot scroll up and down (bounce effect). This parameter is valid only in page configuration. EnablePullDownRefresh Boolean False Whether to enable pull-down refresh, OnPullDownRefresh onReachBottomDistance Number 50 Distance from the bottom of the page when the bottom-pulling event is triggered, in the unit of PX. It triggers the onReachBottom of the page and in addition to onPullDownRefresh and onReachBottom, there’s also onPageScroll, which listens for page scrolling, and the parameter is an object that contains the property scrollTop, Represents the distance (px) that the page has scrolled vertically.
The visual scroll area needs to be realized through the scroll-view, and the CSS property overflow is set to scroll, which cannot be scroll on the real phone.
The scrollview requires a fixed height for vertical scrolling, which can be calC height or Flex height.
The scrollbar setting of the scrollview can be customized using the -webKit-scrollBar of the CSS, including hiding the scrollbar.
In ios, if the scroll view is set, the elastic band rebound effect will appear. The page rebound effect can be disableScroll: If you need to scroll and want to cancel the rebound effect, you can check the scroll state by listening on the events related to the scroll view. In the case of rebound, set the scroll-y to false. To stop the rebound.
For details, please refer to: small program to cancel the elastic band rebound effect solutions and pit summary
Uni also provides the uni.pagescrolltop method to scroll the page to the target location – description
other
Enable wechat debugging tool vConsole and use conditional compilation Settings only for small programs:
//#ifdef MP-WEIXIN
wx.setEnableDebug({
enableDebug: false
})
//#endif
Copy the code
Use CSS styles to enlarge the clickable area:
position: relative;
&:before {
content: '';
position: absolute;
top: -10px; bottom: -10px; left: -10px; right: -10px;
};
Copy the code