How to read the uni app framework efficiently? (recommended Collection)

Posted by rharter on Fri, 22 Nov 2019 20:05:53 +0100

By Jeskson Source: front end tavern of dada

The framework of uni app, configuration: page.json, manifest.json, package.json, vue.config.js. Script, application, main.js. Log printing, timer, life cycle, page, page communication.

pages.json file is used for global configuration of uni app. It is used to write path, window style, tabbar at the bottom, etc. of page file, similar to page management of app.json in applet. What I notice here is the location, which is in app.json in applets, and in uni app, which is configured in manifest. This is what I noticed when I made maps.

pages.json:

{
    "pages": [{
        "path": "pages/component/index",
        "style": {
            "navigationBarTitleText": "assembly"
        }
    }, {
        "path": "pages/API/index",
        "style": {
            "navigationBarTitleText": "Interface"
        }
    }, {
        "path": "pages/component/view/index",
        "style": {
            "navigationBarTitleText": "view"
        }
    }],
    "condition": { //Mode configuration, effective only during development
        "current": 0, //Currently active mode (index entry of list)
        "list": [{
            "name": "test", //Schema name
            "path": "pages/component/view/index" //Start page, required
        }]
    },
    "globalStyle": {
        "navigationBarTextStyle": "black",
        "navigationBarTitleText": "Demonstration",
        "navigationBarBackgroundColor": "#F8F8F8",
        "backgroundColor": "#F8F8F8",
        "usingComponents":{
            "collapse-tree-item":"/components/collapse-tree-item"
        }
    },
    "tabBar": {
        "color": "#7A7E83",
        "selectedColor": "#3cc51f",
        "borderStyle": "black",
        "backgroundColor": "#ffffff",
        "height": "50px",
        "fontSize": "10px",
        "iconWidth": "24px",
        "spacing": "3px",
        "blurEffect": "none|extralight|light|dark", // Blur effect. Do not set the background color when using the blur effect, otherwise the blur effect will fail. The default value is none (only the iOS platform supports HBuilderX 2.4.3 +)
        "list": [{
            "pagePath": "pages/component/index",
            "iconPath": "static/image/icon_component.png",
            "selectedIconPath": "static/image/icon_component_HL.png",
            "text": "assembly"
        }, {
            "pagePath": "pages/API/index",
            "iconPath": "static/image/icon_API.png",
            "selectedIconPath": "static/image/icon_API_HL.png",
            "text": "Interface"
        }],
        "midButton": {
            "width": "80px",
            "height": "50px",
            "text": "Written words",
            "iconPath": "static/image/midButton_iconPath.png",
            "iconWidth": "24px",
            "backgroundImage": "static/image/midButton_backgroundImage.png"
        }
    }
}

Global style, set status bar, navigation bar, title, window background color, etc.

Pages, configure the page path. The first item is the application entry, adding or reducing pages can be modified in the pages array.

┌─pages               
│  ├─index
│  │  └─index.vue    
│  └─login
│     └─login.vue    
├─static             
├─main.js       
├─App.vue          
├─manifest.json  
└─pages.json
{
    "pages": [
        {
            "path": "pages/index/index", 
            "style": { ... }
        }, {
            "path": "pages/login/login", 
            "style": { ... }
        }
    ]
}

Page page

{
  "pages": [{
      "path": "pages/index/index",
      "style": {
        "navigationBarTitleText": "home page",//Set page title text
        "enablePullDownRefresh":true//Enable pull-down refresh
      }
    },
    ...
  ]
}

Common titleNView configuration code examples

{
    "pages": [{
            "path": "pages/index/index", //home page
            "style": {
                "app-plus": {
                    "titleNView": false //Disable native navigation bar
                }
            }
        }, {
            "path": "pages/log/log", //Log page
            "style": {
                "app-plus": {
                    "bounce": "none", //Turn off window bounce
                    "titleNView": {
                        "buttons": [ //Native title bar button configuration,
                            {
                                "text": "share" //Add the share button in the native title bar. Click the event to listen through the onNavigationBarButtonTap function on the page
                            }
                        ]
                    }
                }
            }
        }, {
            "path": "pages/detail/detail", //Details page
            "style": {
                "navigationBarTitleText": "details",
                "app-plus": {
                    "titleNView": {
                        "type": "transparent"//Transparent gradient navigation bar
                    }
                }
            }
        }, {
            "path": "pages/search/search", //Search page
            "style": {
                "app-plus": {
                    "titleNView": {
                        "type": "transparent",//Transparent gradient navigation bar
                        "searchInput": {
                            "backgroundColor": "#fff",
                            "borderRadius": "6px", //Input box fillet
                            "placeholder": "Please enter the search content",
                            "disabled": true //When disable, click the input box to not focus, and you can skip to the new page to search
                        }
                    }
                }
            }
        }
        ...
    ]
}

app-plus,h5,mp-alipay

{
    "pages": [{
        "path": "pages/index/index", //home page
        "style": {
            "app-plus": {
                "titleNView": false , //Disable native navigation bar
                "subNVues":[{//Sideslip menu
                    "id": "drawer", //The id of subNVue can be obtained through uni.getSubNVueById('drawer ')
                    "path": "pages/index/drawer.nvue", // nvue path
                    "style": { //A subset of webview style. Documents can be temporarily opened for location and size related configuration
                        "position": "popup", //In addition to pop, refer to 5+ webview position document for other value fields
                        "width": "50%"
                    }

                }, {//Popup
                    "id": "popup",
                    "path": "pages/index/popup",
                    "style": {
                        "position": "popup",
                        "margin":"auto",
                        "width": "150px",
                        "height": "150px"
                    }

                }, {//Custom header
                    "id": "nav",
                    "path": "pages/index/nav",
                    "style": {
                        "position": "dock",
                        "height": "44px"
                    }

                }]
            }
        }
    }]
}

h5:

titleNView, navigation bar

pullToRefresh, pull-down refresh

tabBar, through the tabBar configuration item, specifies the performance of the tab bar and the corresponding item displayed when the tab is switched.

When the position is set to top, the icon will not be displayed. The list in the tabBar is an array, with at least 2 configured and at most 5 configured.

When tabbar switches to load for the first time, it may not render in time. You can pop a waiting snowflake in the onLoad life cycle of each tabbar page. When the tabbar page is displayed once and the tabbar page is switched again, only onShow will be triggered instead of onLoad.

"tabBar": {
    "color": "#7A7E83",
    "selectedColor": "#3cc51f",
    "borderStyle": "black",
    "backgroundColor": "#ffffff",
    "list": [{
        "pagePath": "pages/component/index",
        "iconPath": "static/image/icon_component.png",
        "selectedIconPath": "static/image/icon_component_HL.png",
        "text": "assembly"
    }, {
        "pagePath": "pages/API/index",
        "iconPath": "static/image/icon_API.png",
        "selectedIconPath": "static/image/icon_API_HL.png",
        "text": "Interface"
    }]
}

condition start mode configuration, valid during development. Property: current is only valid in the currently active mode, the index value of the list node, and the list startup mode list.

"condition": { //Mode configuration, effective only during development
    "current": 0, //Currently active mode (index entry of list)
    "list": [{
            "name": "swiper", //Schema name
            "path": "pages/component/swiper/swiper", //Start page, required
            "query": "interval=4000&autoplay=false" //The startup parameter is obtained in the onLoad function of the page.
        },
        {
            "name": "test",
            "path": "pages/component/switch/switch"
        }
    ]
}

subPackages subcontract load configuration, but in 5+app it is the whole package. The subPackages node receives an array, and each item is a subpackage of the application.

┌─pages               
│  ├─index
│  │  └─index.vue    
│  └─login
│     └─login.vue    
├─pagesA   
│  └─list
│     └─list.vue 
├─pagesB    
│  └─detail
│     └─detail.vue  
├─static             
├─main.js       
├─App.vue          
├─manifest.json  
└─pages.json         
{
    "pages": [{
        "path": "pages/index/index",
        "style": { ...}
    }, {
        "path": "pages/login/login",
        "style": { ...}
    }],
    "subPackages": [{
        "root": "pagesA",
        "pages": [{
            "path": "list/list",
            "style": { ...}
        }]
    }, {
        "root": "pagesB",
        "pages": [{
            "path": "detail/detail",
            "style": { ...}
        }]
    }],
    "preloadRule": {
        "pagesA/list/list": {
            "network": "all",
            "packages": ["__APP__"]
        },
        "pagesB/detail/detail": {
            "network": "all",
            "packages": ["pagesA"]
        }
    }
}

preloadRule subcontract preload configuration. The path of the key page and value are the pre download configuration for entering the page.

The configuration file, application name, icon, permission and so on when the manifest.json file is used.

networkTimeout the timeout of various network requests.

The package.json file is an extension node of uni app, which can implement a custom compilation platform.

{
    /**
     package.json Other original configuration 
     */
    "uni-app": {// Extended configuration
        "scripts": {
            "custom-platform": { //Custom compilation platform configuration, which can be called by cli
                "title":"Custom extension name", // Displayed in the run / release menu in HBuilderX
                "BROWSER":"",  //Target browser to run to, only valid if UNI_PLATFORM is h5
                "env": {//environment variable
                    "UNI_PLATFORM": ""  //Benchmark platform 
                 },
                "define": { //Custom conditional compilation
                    "CUSTOM-CONST": true //Custom conditional compilation constant, uppercase recommended
                }
            }
        }    
    }
}

vue.config.js is an optional configuration file

The uni.css file is a global style. You need to add lang="scss" on the style node when you use it.

<style lang="scss">
</style>

uni.scss variable:

/* Color variable */

/* Behavior related colors */
$uni-color-primary: #007aff;
$uni-color-success: #4cd964;
$uni-color-warning: #f0ad4e;
$uni-color-error: #dd524d;

/* Text basic color */
$uni-text-color:#333; / / basic color
$uni-text-color-inverse:#fff; / / anti color
$uni-text-color-grey:#999; / / auxiliary gray, such as loading more tips
$uni-text-color-placeholder: #808080;
$uni-text-color-disable:#c0c0c0;

/* background color */
$uni-bg-color:#ffffff;
$uni-bg-color-grey:#f8f8f8;
$uni-bg-color-hover:#f1f1f1; / / click the status color
$uni-bg-color-mask:rgba(0, 0, 0, 0.4);//Mask color

/* Border color */
$uni-border-color:#c8c7cc;

/* Dimension variable */

/* Text size */
$uni-font-size-sm:24rpx;
$uni-font-size-base:28rpx;
$uni-font-size-lg:32rpx;

/* Picture size */
$uni-img-size-sm:40rpx;
$uni-img-size-base:52rpx;
$uni-img-size-lg:80rpx;

/* Border Radius */
$uni-border-radius-sm: 4rpx;
$uni-border-radius-base: 6rpx;
$uni-border-radius-lg: 12rpx;
$uni-border-radius-circle: 50%;

/* Horizontal spacing */
$uni-spacing-row-sm: 10px;
$uni-spacing-row-base: 20rpx;
$uni-spacing-row-lg: 30rpx;

/* Vertical spacing */
$uni-spacing-col-sm: 8rpx;
$uni-spacing-col-base: 16rpx;
$uni-spacing-col-lg: 24rpx;

/* transparency */
$uni-opacity-disabled: 0.3; // Transparency of disabled components

/* Article scenario related */
$uni-color-title: #2C405A; / / article title color
$uni-font-size-title:40rpx;
$uni-color-subtitle: #55555; / / secondary Title Color
$uni-font-size-subtitle:36rpx;
$uni-color-paragraph: #3F536E; / / article paragraph color
$uni-font-size-paragraph:30rpx;

app.vue is the entry file of our page.

Application lifecycle:

onLaunch: triggered once when uni app initialization is completed; onShow: triggered when uni app is started or enters the foreground display from the background; onHide: triggered when uni app enters the background from the foreground; onError: triggered when uni app reports an error; onUniNViewMessage: monitored the data sent by nvue page.

<script>  
    export default {  
        onLaunch: function() {  
            console.log('App Launch')  
        },  
        onShow: function() {  
            console.log('App Show')  
        },  
        onHide: function() {  
            console.log('App Hide')  
        }  
    }  
</script>

The mechanism of applets in global data is also available in uni app.

App.vue configuration:

<script>  
    export default {  
        globalData: {  
            text: 'text'  
        }
    }  
</script>

Obtain:

getApp().globalData.text = 'test'

The getApp object has not been obtained. You can use the

this.$scope.globalData Obtain globalData

When main.js is the entry file, it initializes the vue instance and uses the required plug-ins.

import Vue from 'vue'
import App from './App'
import pageHead from './components/page-head.vue' //Reference page head component

Vue.config.productionTip = false
Vue.component('page-head', pageHead) //Global registration page head component
App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount() //Mount Vue instance

Print log: console prints log information to console, debug prints debug log to console, log prints log log to console, info,warn,error prints to console respectively, info,warn,error logs.

SetTimeout timer, execute after the time, clearTimeout cancels the timer set by setTimeout, setInterval() sets a timer, clearInterval() cancels the timer set by setInterval.

Application lifecycle:

onLaunch Triggered when uni app initialization is complete, only once for the global

onShow When the uni app starts, or enters the foreground display from the background

onHide When uni app enters the background from the foreground

onError Triggered when uni app reports an error

onUniNViewMessage Monitor the data sent by nvue page

<script>
    // Only monitor the application's life cycle in App.vue
    export default {
        onLaunch: function() {
            console.log('App Launch')
        },
        onShow: function() {
            console.log('App Show')
        },
        onHide: function() {
            console.log('App Hide')
        }
    }
</script>

Page lifecycle

onLoad Monitor page loading

onShow Monitor page display

onReady Listening page first rendering completed

onHide Monitor page hidden

onUnload Monitor page uninstall

onResize Monitor window size change

onPullDownRefresh Monitor user pull-down action

onReachBottom Events at the bottom of the page

onTabItemTap Triggered when you click the tab. The parameter is Object

onShareAppMessage Users click the upper right corner to share

onPageScroll Monitor page scrolling

onNavigationBarButtonTap Listen to native title bar button click event

onBackPress Monitor page return

onNavigationBarSearchInputChanged Listen to the event of change of input content in the search input box of the native title bar

onNavigationBarSearchInputConfirmed Listen to the search event in the search input box of the native title bar. It is triggered when the user clicks the "search" button on the soft keyboard

onNavigationBarSearchInputClicked Listen to the click event in the search input box of the native title bar

Component lifecycle

The life cycle supported by uni app components is the same as that of vue standard components.

beforeCreate Called after instance initialization created Called immediately after instance creation

beforeMount Called before mount starts mounted When mounted to an instance, it is called.

beforeUpdate Called on data update updated

beforeDestroy Call before instance destruction destroyed Call after instance destruction

getApp() Function to get the current application instance

const app = getApp() console.log(app.globalData)

getCurrentPages() Function to get an instance of the current page stack

navigateTo, redirectTo can only open non tabBar pages.

switchTab can only open tabBar pages.

reLaunch can open any page.

getCurrentPages()

The obtained page contains a method $getAppWebview() to get the object instance of the current webview

getCurrentPages()

All page objects can be obtained, and then the specified page webview object can be obtained according to the array

uni.$emit

Trigger global custom events

uni.$on

Listen to global custom events

uni.$once

Listen to global custom events, which can be triggered by uni.$emit, but only once

uni.$off remove global custom event listener

uni.$emit('update',{msg:'Page update'})
uni.$on('update',function(data){
        console.log('Listening for events from update ,Portability parameter msg For:' + data.msg);
})
uni.$once('update',function(data){
        console.log('Listening for events from update ,Portability parameter msg For:' + data.msg);
})

❤ don't forget to leave your footprints of learning Author Info:

[author]: Jeskson

Original public address: dada's front bar.

[reprint description]: please explain the source of reprint, thank you for your cooperation! ~

About the content of the current article that involves the front-end, PHP knowledge points, if you are interested in it, you can pay attention to it. It's a great honor to be found by you. It's really smart to know English! Thank you for your attention. In the future, I hope to support me silently all the time, and I will try to write more excellent works. We grow up together, from zero basic programming, to present the Web front-end field, data structure and algorithm, network principle and other easy to understand to small partners. Share technical articles, tool resources, selected courses and hot information related to Web front-end.

If the content of this number is not in place (for example, involving copyright or other issues), please contact us in time for rectification, and we will deal with it as soon as possible.

Please praise! Because your approval / encouragement is the biggest driving force of my writing!

Welcome to your attention. Dada CSDN!

This is a blog with quality and attitude

Topics: Front-end Vue JSON network iOS