Uni app knowledge points sorting

I Company
1. Conversion rules:

	1 px = 2 rpx
	1 px = 0.75 pt = 3 / 4 pt
	1 pt = 1.33 px =  4 / 3 px = 8 / 3 rpx
	1 em = 16 px
	1 em = 12 pt
	1px = 1pt * Image resolution/72

rpx is calculated based on the ratio of the current screen width to 750, which is dynamic. It will be converted according to different screens. So it's easier to use a response.

pt (point, pound): it is a unit of physical length, which refers to 72th of an inch.
px (pixel): pixel px is relative to the resolution of the display screen.
PX features

  1. IE cannot adjust the font size using px as the unit;
  2. Most foreign websites can be adjusted because they use em or rem as font units;
  3. Firefox can adjust px, em and rem, but more than 96% of Chinese Internet users use IE browser (or kernel).
    EM (relative length unit, relative to the font size of the text in the current object): it is a relative length unit, which initially refers to the width of the letter M, so it is named em. Now it refers to the multiple of character width. The usage is similar to percentage, such as 0.8em, 1.2em,2em, etc. Usually 1em=16px.
    EM features
  4. The value of em is not fixed;
  5. em inherits the font size of the parent element.
    Note: the default font height of any browser is 16px. All unadjusted browsers comply with: 1em=16px. Then 12px=0.75em,10px=0.625em. In order to simplify the conversion of font size, you need to declare font size = 62.5% in the body selector in css, which changes the EM value to 16px*62.5%=10px, so 12px=1.2em, 10px=1em, that is, you only need to divide your original PX value by 10, and then replace em as the unit.
    So when we write CSS, we need to pay attention to two points:
  6. Declare font size = 62.5% in the body selector;
  7. Divide your original px value by 10 and replace it with em;
  8. Recalculate the em value of those enlarged fonts. Avoid duplicate declarations of font size.
    That is to avoid the phenomenon of 1.2 * 1.2 = 1.44. For example, if you declare a font size of 1.2em in #content, the font size of p can only be 1em instead of 1.2em. Because this EM is not the other em, it becomes 1em=12px due to the inherited font height of #content.
    Font size: it is a unique unit in the Chinese font. The Chinese code represents the specific point value pt, which is convenient for memory and expression.
    The conversion formula of pt and px can be obtained according to the definition of pt:
    PT = 1 / 72 (inch), PX = 1 / DPI (inch)

Rem is a new relative unit (root em, root EM) in CSS3, which has attracted extensive attention. What is the difference between this unit and em? The difference is that when rem is used to set the font size for the element, it is still the relative size, but the relative is only the HTML root element. This unit combines the advantages of relative size and absolute size. It can not only adjust all font sizes proportionally by modifying the root element, but also avoid the chain reaction of font size compounding layer by layer. At present, all browsers except IE8 and earlier have supported rem. For browsers that do not support it, the response is also very simple, that is, write an additional declaration of absolute units. These browsers ignore the font size set with rem. Here is an example:
p {font-size:14px; font-size:.875rem;}
Note: the choice of font unit is mainly determined by your project. If your user group uses the latest browser, rem is recommended. If compatibility is to be considered, px or both.
The choice of px and rem?
For those that only need to adapt to a small number of mobile devices and the resolution has little impact on the page, use px.
For various mobile devices that need to be adapted, rem is used. For example, only devices with large resolution differences such as iPhone and iPad need to be adapted.

II CSS

1. Get status bar height bangs
 this.iStatusBarHeight = uni.getSystemInfoSync().statusBarHeight
 var(--status-bar-height) This variable is fixed in wechat applet environment px,stay App Inside is the height of the actual status bar of the mobile phone.
2. Absolute Centering  
	 1,Mainstream with good compatibility css Usage of absolute positioning center:
	.conter{
	width:600px;
	height:400px;
	position:absolute;
	left:50%;
	top:50%;
	margin-top:-200px;/*Half the height*/
	margin-left:-300px;/*Half the width*/
 }
Note: one obvious disadvantage of this method is that the size of elements needs to be known in advance. otherwise margin Negative values cannot be adjusted accurately. At this time, it is often necessary to use JS get.
2,css3 With the emergence of, a better solution is to use transform replace margin.transform in translate The percentage value of the offset is relative to its own size, which can be achieved in this way css Absolute positioning center:
.conter{
	width:600px;height:400px;
	position:absolute;
	left:50%;
	top:50%;
	transform:translate(-50%,-50%);/*50%Half its size*/
}
3,margin:auto Realize the centering of absolute positioning elements(Up, down, left and right are positioned at 0 position; margin:auto)
.conter{
	width:600px;
	height:400px;
	position:absolute;
	left:0;
	top:0;
	right:0;
	bottom:0;
	margin:auto;/*With this, it will be centered automatically*/
}
 
 CSS position Relative positioning and absolute positioning:
 https://www.runoob.com/w3cnote/css-position-static-relative-absolute-fixed.html

III Time class

1.Get current timestamp
Math.round(new Date() / 1000)

IV Equipment https://uniapp.dcloud.io/api/system/info

text message
uni.getSystemInfo({
success: function (res) {
    console.log(res.model);
    console.log(res.pixelRatio);
    console.log(res.windowWidth);
    console.log(res.windowHeight);
    console.log(res.language);
    console.log(res.version);
    console.log(res.platform);
}
});
system information 
try {
	const res = uni.getSystemInfoSync();
	console.log(res.model);
	console.log(res.pixelRatio);
	console.log(res.windowWidth);
	console.log(res.windowHeight);
    console.log(res.language);
    console.log(res.version);
    console.log(res.platform);
} catch (e) {
	// error
}

Obtain the current APP version information and version upgrade

overall situation APP.vue In the file
export default {
		data() {
			return {
	
		}
	},
	onLaunch: function() {
		console.log('App Launch start-up')
		// #ifdef APP-PLUS
		// Get manifest JSON information
		plus.runtime.getProperty( plus.runtime.appid, function ( wgtinfo ) {
		    //  Get app version
		    let appversion = wgtinfo.version;
		    // Cache version number
		    try {
		        uni.setStorageSync('appversion', appversion);
		    } catch (e) {}
		});
		//to update
		 this.checkUpdate();
		// #endif
		         
	},
	onShow: function() {
		console.log('App Show Displayed at the front desk')
	},
	onHide: function() {
		console.log('App Hide Not at the front desk')
	},
	
	methods: {
		// Version upgrade
		// #ifdef APP-PLUS
		checkUpdate(){
			var curVersion = uni.getStorageSync('appversion')
			console.log(curVersion);
			// Update version interface  
			var server = "http://t.heijinka.vip/api/version"; 
			var that = this;
			
			uni.request({
			    url: server,  //Request update address
			    data: that.curVersion,
			    success(res) {
			        if (res.statusCode == 200 && that.curVersion < res.data.msg.version) {
			            uni.showModal({
			                title: 'Version update' + res.data.msg.version,
			                content: res.data.msg.content,
			                confirmText: "to update",
			                // showCancel: !res.forceUpdate,
			                success: function(e) {
			                    if (e.confirm) {
			                        if (plus.os.name.toLowerCase() == 'ios') {
			                            // Jump to download page
			                            plus.runtime.openURL(res.data.msg.downloadUrl)
			                        } else {
			                            that.createDownload(res.data.msg.downloadUrl);
			                        }
			                    } else {
			                        //cancel
			                    }
			                }
			            });
			        } else {
			            uni.showModal({
			                title: 'Tips',
			                content: 'Is the latest version',
			                showCancel: false
			            });
			        }
			    },
			})    
			
		},
		    
		createDownload(url){
			var dtask = plus.downloader.createDownload(url, {},
				function(d, status) {
					uni.showToast({
						title: 'Download complete',
						mask: false,
						duration: 1000
					});
					//console.log(dtask);
					// Download complete
					console.log('status: '+status);
					if (status == 200) {
						console.log('Download succeeded:'+d.filename);
						console.log('plus.io.convertLocalFileSystemURL(d.filename): '+plus.io.convertLocalFileSystemURL(d.filename))
						plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, function(success) {
							uni.showToast({
								title: 'Installation succeeded',
								mask: false,
								duration: 1500
							});
						}, function(error) {
							uni.showToast({
								title: 'Installation failed-01',
								mask: false,
								duration: 1500
							});
						})
					} else {
						uni.showToast({
							title: 'Update failed-02',
							mask: false,
							duration: 1500
						});
					}
			});
			try {
				dtask.start(); // Open download task
				var prg = 0;
				var showLoading = plus.nativeUI.showWaiting("Downloading");  //Create a showWaiting object 
				dtask.addEventListener('statechanged', function(task,status) {
					// Set a monitor for the download task and operate according to the status
					switch (task.state) {
						case 1:
							showLoading.setTitle("Downloading");
							break;
						case 2:
							showLoading.setTitle("Connected to server");
							break;
						case 3:
							prg = parseInt((parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) * 100 );
							showLoading.setTitle("  Downloading" + prg + "%  ");
							break;
						case 4:
							plus.nativeUI.closeWaiting();
							//Download complete
							break;
					}
				});
			  } catch (err) {
				plus.nativeUI.closeWaiting();
				uni.showToast({
					title: 'Update failed-03',
					mask: false,
					duration: 1500
				});
			}
		},	    
		//#endif  
	}           
	
}

Safety distance at the bottom of label bar height

topSafe:  
uni.getSystemInfoSync().statusBarHeight;
var(--status-bar-height)
bottomSafe:
bottom: var(--window-bottom) ;
bottom: calc(var(--window-bottom) + 44px);

Applet version number

const accountInfo = wx.getAccountInfoSync(); 

Get system information

uni.getSystemInfo({
	success(res) {
		console.log(res);
}
})

Jump to application market and App Store
//This is a general application market. If you want to specify an application store, you need to check the package name or scheme and parameters of the application store separately

if (plus.os.name == "Android") {
    let appurl = "market://details?id = package name for self packaging "; 
    plus.runtime.openURL(appurl);
}

//Jump to use treasure

 let appurl = "market://details?id = package name for self packaging ";
 plus.runtime.openURL(appurl,(err) =>{
	console.log('Failed to open application treasure', err);
 },'com.tencent.android.qqdownloader');

//How to open external applications in uni app, such as browser, Taobao, AppStore, QQ, etc
Open a third-party program
The URL specified by the external browser to open

plus.runtime.openURL( url, errorCB, identity );  

URL: (string) required. Select the URL address string type to open. The address types supported by each platform are different. Refer to the platform URL support table.
Errorcb: (openerrorcallback) optional. Open the callback of URL address failure. Open the callback when the specified URL address fails and return the failure information.
Identity: (string) optional. Specify the program name of the opening URL address. This parameter is ignored on iOS platform. It is the package name on Android platform. If the specified package name does not exist, opening the URL address fails.


< button class = "button" type = "primary" @ click = "open(0)" > use a third-party program to open the specified URL

<script>
	export default {
		data() {
			return {
				url: 'https://uniapp.dcloud.io/'  
			}
		},
		methods: {
			open(types) {  
				plus.runtime.openURL(this.url, function(res) {
					cosole.log(res);  
				});  
			}  
		}
	}
</script>

Calling third-party programs

plus.runtime.launchApplication( appInf, errorCB );  

Appinf: (applicationif) required description of the third-party program to start
Errorcb: (launchererrorcallback) required. Select the callback function that failed to start the third-party program. When the third-party program fails to start, call back and return the failure information.

<template>
	<view>
		 <button class="button" type="primary" @click="launchApp">Open Taobao</button>  
	</view>
</template>
<script>
	export default {
		data() {
			return {
				url: 'https://uniapp.dcloud.io/'  
			}
		},
		methods: {
			launchApp() {  
			    let _this = this;
			    // Judgment platform
			    if (plus.os.name == 'Android') {  
			        plus.runtime.launchApplication(  
			            {  
			                pname: 'com.taobao.taobao'  
			            },  
			            function(e) {  
			                console.log('Open system default browser failed: ' + e.message);  
			            }  
			        );  
			    } else if (plus.os.name == 'iOS') {  
			        plus.runtime.launchApplication({ action: 'taobao://' }, function(e) {  
			            console.log('Open system default browser failed: ' + e.message);  
			        });  
			    }      
			    			
			}            
		}
	}
</script>

Common URLscheme
[
//Effective only in ios
{
name: 'App Store',
scheme: 'itms-apps://'
},
{
name: 'Alipay',
pname: 'com.eg.android.AlipayGphone',
scheme: 'alipay://'
},
{
name: 'Taobao',
pname: 'com.taobao.taobao',
scheme: 'taobao://'
},
{
name: 'QQ',
pname: 'com.tencent.mobileqq',
scheme: 'mqq://'
},
{
name: 'wechat',
pname: 'com.tencent.mm',
scheme: 'weixin://'
},
{
name: 'Jingdong',
pname: 'com.jingdong.app.mall',
scheme: 'openApp.jdMobile://'
},
{
name: 'Sina Weibo',
pname: 'com.sina.weibo',
scheme: 'sinaweibo://'
},
{
name: 'Youku',
pname: 'com.youku.phone',
scheme: 'youku://'
}
]
More practical examples
In addition to simply opening the App, we often want direct access. Here are many useful direct cases:
Use the App store to open the specified App, which can be used to guide scoring
Force to use App treasure to open the specified App
Open the Taobao Search page. To be a Taobao customer, you need to apply for your own scheme parameter from Taobao and pass it in.
Open the map and specify a location
Open qq and go to the specified chat interface, which can be used for customer service. The specific code is shown below:

<template>  
    <view>  
        <page-head title="adopt scheme Open third party app Examples"></page-head>  
        <button class="button" @click="openBrowser('https://uniapp. dcloud. IO / H5 ') "> open the specified URL with a browser < / button >  
        <button class="button" @click="openMarket()">Use the store to open the specified App</button>  
        <button class="button" @click="openMarket('com.tencent.android.qqdownloader')">Force app to open specified App</button>  
        <button class="button" @click="openTaobao('taobao://s.taobao. com/search? Q = uni app ') "> Open Taobao Search page < / button >  
        <button class="button" @click="openMap()">Open the map and specify a location</button>  
        <view class="uni-divider">  
            <view class="uni-divider__content">open QQ</view>  
            <view class="uni-divider__line"></view>  
        </view>  
        <view class="uni-padding-wrap">  
            <form @submit="openQQ">  
                <view>  
                    <view class="uni-title">Please enter a chat object QQ number:</view>  
                    <view class="uni-list">  
                        <view class="uni-list-cell">  
                            <input class="uni-input" name="qqNum" type="number"/>  
                        </view>  
                    </view>  
                </view>  
                <view>  
                    <view class="uni-title">Please select QQ Number type:</view>  
                    <radio-group class="uni-flex" name="qqNumType">  
                        <label>  
                            <radio value="wpa" checked=""/>ordinary QQ number</label>  
                        <label>  
                            <radio value="crm" />Marketing QQ number(Chat directly without adding friends)</label>  
                    </radio-group>  
                </view>  
                <view class="uni-btn-v uni-common-mt">  
                    <button class="button" formType="submit">open qq And go to the specified chat interface</button>  
                </view>  
            </form>  
        </view>  
    </view>  </template>  
<script>  export default {  
    data() {  
        return {  

        };  
    },  
    methods: {  
        openBrowser(url){  
            plus.runtime.openURL(url)  
        },  
        openMarket(marketPackageName) {  
            var appurl;  
            if (plus.os.name=="Android") {  
                appurl = "market://details?id=io.dcloud.HelloH5 "  
            }  
            else{  
                appurl = "itms-apps://itunes.apple.com/cn/app/hello-uni-app/id1417078253?mt=8";  
            }  
            if (typeof(marketPackageName)=="undefined") {  
                plus.runtime.openURL(appurl, function(res) {  
                    console.log(res);  
                });  
            } else{//Forcibly specify the package name of an Android application market, and start the specified app through this package name  
                if (plus.os.name=="Android") {  
                    plus.runtime.openURL(appurl, function(res) {  
                        plus.nativeUI.alert("There is no app installed on this machine");  
                    },marketPackageName);  
                } else{  
                    plus.nativeUI.alert("only Android Only mobile phones support app treasure");  
                }  
            }  
        },  
        openTaobao(url){  
            plus.runtime.openURL(url, function(res) {  
                uni.showModal({  
                    content:"Taobao client is not detected on this machine. Do you want to open the browser to access Taobao?",  
                    success:function(res){  
                        if (res.confirm) {  
                            plus.runtime.openURL("https://s.taobao.com/search?q=uni-app")  
                        }  
                    }  
                })  
            });  
        },  
        openMap(){  
            var url = "";  
            if (plus.os.name=="Android") {  
                var hasBaiduMap = plus.runtime.isApplicationExist({pname:'com.baidu.BaiduMap',action:'baidumap://'});  
                var hasAmap = plus.runtime.isApplicationExist({pname:'com.autonavi.minimap',action:'androidamap://'});  
                var urlBaiduMap = "baidumap://map/marker?location=39.968789,116.347247&title=DCloud&src=Hello%20uni-app";  
                var urlAmap = "androidamap://viewMap?sourceApplication=Hello%20uni-app&poiname=DCloud&lat=39.9631018208&lon=116.3406135236&dev=0"  
                if (hasAmap && hasBaiduMap) {  
                    plus.nativeUI.actionSheet({title:"Select Map Application",cancel:"cancel",buttons:[{title:"Baidu Maps"},{title:"Gaude map"}]}, function(e){  
                        switch (e.index){  
                            case 1:  
                                plus.runtime.openURL(urlBaiduMap);  
                                break;  
                            case 2:  
                                plus.runtime.openURL(urlAmap);  
                                break;  
                        }  
                    })  
                }  
                else if (hasAmap) {  
                    plus.runtime.openURL(urlAmap);  
                }  
                else if (hasBaiduMap) {  
                    plus.runtime.openURL(urlBaiduMap);  
                }  
                else{  
                    url = "geo:39.96310,116.340698?q=%e6%95%b0%e5%ad%97%e5%a4%a9%e5%a0%82";  
                    plus.runtime.openURL(url); //If it is a foreign application, it should be used first. It will start google maps. This interface cannot unify the coordinate system, and there will be deviation when entering Baidu map  
                }  
            } else{  
                // To obtain whether Baidu Gaode map is installed on this machine on iOS, you need to configure it in manifest JSON file is added under the app plus - > distribute - > Apple - > urlschemewhitelist node (such as urlschemewhitelist: ["iosamap", "Baidu map"])  
                plus.nativeUI.actionSheet({title:"Select Map Application",cancel:"cancel",buttons:[{title:"Apple Map"},{title:"Baidu Maps"},{title:"Gaude map"}]}, function(e){  
                    console.log("e.index: " + e.index);  
                    switch (e.index){  
                        case 1:  
                            url = "http://maps.apple.com/?q=%e6%95%b0%e5%ad%97%e5%a4%a9%e5%a0%82&ll=39.96310,116.340698&spn=0.008766,0.019441";  
                            break;  
                        case 2:  
                            url = "baidumap://map/marker?location=39.968789,116.347247&title=DCloud&src=Hello%20uni-app";  
                            break;  
                        case 3:  
                            url = "iosamap://viewMap?sourceApplication=Hello%20uni-app&poiname=DCloud&lat=39.9631018208&lon=116.3406135236&dev=0";  
                            break;  
                        default:  
                            break;  
                    }  
                    if (url!="") {  
                        plus.runtime.openURL( url, function( e ) {  
                            plus.nativeUI.alert("The specified map app is not installed on this computer");  
                        });  
                    }  
                })  
            }  
        },  
        openQQ: function (e) {  
            // console.log("e.detail.value: " + JSON.stringify(e.detail.value));  
            // It is not verified whether the qq number is empty or legal. If it is not an available qq number, it will stay in the qq main interface after starting qq  
            plus.runtime.openURL('mqqwpa://im/chat?chat_type=' + e.detail.value.qqNumType + '&uin=' + e.detail.value.qqNum,function (res) {  
                plus.nativeUI.alert("This machine is not installed QQ,Unable to start");  
            });  
        }  
    }  
};  </script>  <style>  .button {  
    margin: 30upx;  
    color: #007AFF;  
}  </style>  

Set scheme for your App
It can be configured in manifest. Android configuration method iOS configuration method
Uni app jump to ios app store

plus.runtime.launchApplication({
    action: 'https://itunes.apple.com/cn/app/xxx-xxx-xx-xx/idxxxxxxxxxx?mt=8'
//Address: action: `itms-apps://itunes.apple.com/cn/app/id${appleId}?mt=8`
//Address: https://apps.apple.com/cn/app/%E6%9C%9B%E6%B5%B7%E4%BA%BA/id1514736394
}, function(e) {
    console.log('Open system default browser failed: ' + e.message);
  });

Four ways to implement uni app global variables
Common module
Define a special module to organize and manage these global variables and introduce them in the required pages.
Note: this method only supports the sharing of multiple vue pages or multiple nvue pages, but not between vue and nvue.

Create a common directory under the root directory and create XX JS define common methods

const websiteUrl = 'http://www.javanx.cn';  
const now = Date.now || function () {  
  return new Date().getTime();  
};  
const isArray = Array.isArray || function (obj) {  
  return obj instanceof Array;  
};  
export default {  
  websiteUrl,  
  now,  
  isArray  
}

Next, in pages / index / index The module is referenced in Vue

<script>
 import helper from '/common/base.js'; 

export default { 
data() { 
return {}; 
}, 
onLoad(){ 
console.log('now:' + helper.now()); 
}, 
methods: { } 
}
 </script> 

This method is convenient to maintain, but the disadvantage is that it needs to be introduced every time.
II Mount Vue prototype
Some constants or methods that are frequently used are directly extended to Vue On prototype, each Vue object will "inherit".
Note that this method only supports the sharing of multiple vue pages or multiple nvue pages, but not between vue and nvue.
In main Attaching properties / methods in JS

Vue.prototype.websiteUrl = 'http://www.javanx.cn';  
Vue.prototype.now = Date.now || function () {  
  return new Date().getTime();  
};  
Vue.prototype.isArray = Array.isArray || function (obj) {  
  return obj instanceof Array;  
}; 

Then in pages / index / index Call in Vue

<script>  
export default {  
  	data() {  
    		return {};  
  	},  
  	onLoad(){  
    	console.log('now:' + this.now());  
  	},  
  	methods: {  
  	}  
}  
</script>  

In this way, you only need to be in main JS can be directly called in each page.
Note: 1. Do not duplicate attribute or method names in each page.
2. Recommended in Vue Attributes or methods mounted on prototype can be prefixed with a uniform prefix. For example, $url, global_ In this way, the url can be easily distinguished from the content of the current page when reading the code.

III globalData
In applet, global variables can be declared on App, but not in Vue, and in uni App, in App Vue can be defined on the globalData attribute, or it can be read and written using the API.
This method supports vue and nvue to share data. It is a better way for nvue and vue to share data.
Definition: app vue

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

/*Public css for each page*/

The operation of globalData in js is as follows:
Assignment:
getApp().globalData.text = 'test'
Value:
console.log(getApp().globalData.text)// test

If you need to bind the data of globalData to the page, you can re assign the variable in the onshow declaration cycle of the page. Since HBuilderX 2.0.3, the nvue page also supports onshow in the uni app compilation mode.

IV Vuex
Vuex is designed for Vue JS application development state management mode. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way.
Note that this method only supports the sharing of multiple vue pages or multiple nvue pages, but not between vue and nvue.
Here, take the synchronous update of user information after login as an example to briefly explain the usage of Vuex. For more detailed content of Vuex, it is recommended to go to its official website Vuex to learn.
Create a new store directory under the root directory of the uni app project, and create an index JS defines the status value

const store = new Vuex.Store({  
  state: {  
    login: false,  
    token: '',  
    avatarUrl: '',  
    userName: ''  
  },  
  mutations: {  
    login(state, provider) {  
      console.log(state)  
      console.log(provider)  
      state.login = true;  
      state.token = provider.token;  
      state.userName = provider.userName;  
      state.avatarUrl = provider.avatarUrl;  
    },  
    logout(state) {  
      state.login = false;  
      state.token = '';  
      state.userName = '';  
      state.avatarUrl = '';  
    }  
  }  }) 

Then, you need to be in main JS mount Vuex

import store from './store'  
Vue.prototype.$store = store  
Finally, in pages/index/index.vue use
<script>  
import {  
  mapState,  
  mapMutations  } from 'vuex';  
export default {  
  	computed: {  
    		...mapState(['avatarUrl', 'login', 'userName'])  
  	},  
  	methods: {  
    		...mapMutations(['logout'])  
  	}  
}  
</script>  

For detailed examples, please download the attachment and run it in HBuilderX.
Example operation steps: prompt to log in when you are not logged in. After jumping to the login page, click "login" to obtain user information. After updating the status synchronously, return to the personal center to see the results of information synchronization.
Note: compared with the previous method, this method is more suitable for dealing with global situations where the value will change.

1,. vue and Nvue is not a specification, so some are in The scheme applicable in vue does not apply to nvue.
2. Mount properties on Vue, not on Used in nvue.
3,. nvue does not support vuex
4. If you wish vue and In some schemes of. vue, it is necessary to adopt the method of reuse respectively vue and nvue file.

Timer usage and clearing
Define a timer

data() {
	return {
	timer: null
	}
}

set timer

this.timer = setTimeout( () => {
//Add processing logic

}, duration*1000) 

this.timer = setInterval( () => {
//Add processing logic

}, 1000)

Clear the timer. Note that the timer is used in our page. When you leave this page, you must remember to clear it to avoid bug s.

onUnload() {
	if (this.timer) {
	clearTimeout(this.timer);
	this.timer = null;
	}
}
tabbar Page use onHide
onOnHide() {
	if (this.timer) {
	clearTimeout(this.timer);
	this.timer = null;
	}
}

Remove the navigation bar
page.json

Remove all pages:

"globalStyle": {
		"navigationBarTextStyle": "white",
		"navigationBarTitleText": "uni-app",
		"navigationBarBackgroundColor": "#007AFF",
		"backgroundColor": "#F8F8F8",
"navigationStyle":"custom",	"app-plus":{		"titleView":false	}
	},
Single page removal:
{
	"path" : "pages/loginView/messageView",
	"style" : {
		       "navigationBarTitleText": "SMS login",
		        "enablePullDownRefresh": false,
				"navigationStyle":"custom",  
				"app-plus": { 
					"titleNView":  false   
				}
		}
}

How to introduce Echarts into uni app
Directly install the ecarts plug-in through the official website of uni app to generate the ecarts project template;
Create a new Hello uni app project template;
Put ecarts into components.
Introducing echarts

<template>
	<view class="container">
		<view>
			<view class="canvasView">
				<mpvue-echarts class="ec-canvas" @onInit="lineInit" canvasId="line" ref="lineChart" />
			</view>
		</view>
	</view>
</template>

<script>
	// import * as echarts from '@/components/echarts/echarts.simple.min.js';
	    // import mpvueEcharts from '@/components/mpvue-echarts/src/echarts.vue';
	import * as echarts from '../echarts/echarts.simple.min.js'
	import mpvueEcharts from '../mpvue-echarts/src/echarts.vue'
	
	export default {
		data() {
			return {
				updateStatus: false,
				line: {
					legend: {
						data: ['Mail marketing'],
					},
					xAxis: {
						type: 'category',
						data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
				    },
					yAxis: {
						type: 'value',
						data: [],
					},
					dataZoom: [{            
						type: 'slider',                        
						start: 30,                        
						end: 100,                        
						zoomLock: false,                    
					}],
					grid: {
						left: 40,
						right: 40,
						bottom: 20,
						top: 40,
						containLabel: true,
					},
					series: [{                        
						data: [],
						data: [820, 932, 901, 934, 1290, 1330, 1320],
						type: 'line',
						color: ['#5eb4e2 '], / / color of broken line
					}]
				}
			}
		},
		methods: {
			lineInit(e) {
				let {
					width,
					height
					} = e;
					let canvas = this.$refs.lineChart.canvas
					echarts.setCanvasCreator(() => canvas);
			        let lineChart = echarts.init(canvas, null, {
						width: width,
						height: height,
					})
					canvas.setChart(lineChart)
					lineChart.setOption(this.line)
					this.$refs.lineChart.setChart(lineChart)
			      },
		},
		components: {
			mpvueEcharts
		 }
	}
</script>

<style>
	.ec-canvas {
        display: flex;
        height: 100%;
        flex: 1;
    }
  
    .canvasView {
        width: 700upx;
        height: 500upx;
    }
</style>

Customize components and messaging between components
Before customizing a component, you need to create a components directory in the project directory. Right click the components directory and select new component. When creating a component, you can select a template or click Customize template in the upper right corner to create a template name in the pop-up directory txt, you can write the contents of the template inside, such as creating a template with attributes txt as follows:

<template name="Component name">
	<text style="text-decoration:underline" :href="href" @click="openURL" :inWhiteList="inWhiteList">{{text}}</text>
</template>

<script>
	/**
	 * @description u-link It is an external web page hyperlink component. Open the internal web view component or copy the url in the applet, open the external browser in the app, and open a new web page at the h5 end
	 * @property {String} href The url of the external web page opened after clicking must start with https: / / in the applet
	 * @property {String} text Displayed text
	 * @property {Boolean} inWhiteList Whether it is in the applet white list. If it is, the built-in web view will be directly opened on the applet side. Otherwise, it will only copy the url and prompt to open it externally
	 * @example * <u-link href="https://ext.dcloud.net.cn" text="https://ext.dcloud.net.cn" :inWhiteList="true"></u-link>
	 */
	export default {
		name: 'u-link',  //"Component name"
//attribute
		props: {
			href: {// Attribute name
				type: String, //Attribute type
				default: ''
			},
			text: {
				type: String,
				default: ''
			},
			inWhiteList: {
				type: Boolean,
				default: false
			}
		},
		methods: {
			openURL() {
				// #ifdef APP-PLUS
				plus.runtime.openURL(this.href) //Here, the default is to use the external browser instead of the internal web view component
				// #endif
				// #ifdef H5
				window.open(this.href)
				// #endif
				// #ifdef MP
				if (this.inWhiteList) { //If it is in the URL white list of the applet, it will go through the built-in webview to open it, otherwise it will copy the URL prompt and open it in an external browser
					uni.navigateTo({
						url: '/pages/component/web-view/web-view?url=' + this.href
					});
				} else {
					uni.setClipboardData({
						data: this.href
					});
					uni.showModal({
						content: 'This website cannot be opened directly in an applet. The web address has been automatically copied. Please paste it in the mobile browser',
						showCancel: false
					});
				}
				// #endif
			}
		}
	}
</script>

<style>

</style>


In the page that needs to use custom components, first import custom components, as follows:

import u-link from '../../components/u-link.vue';

Then register the component on the current page, as follows:
components: {    u-link}
Last use, such as index.vue As follows:
<template>
<view>
	<u-link class="hello-link" :href="'https://uniapp.dcloud.io/api/'" :text="'https://uniapp.dcloud.io/api/'"
                    :inWhiteList="true"></u-link>
</view>
</template>
<script>
//import u-link from '../../components/u-link.vue';
export default {
data() {
return {

}
},

onLoad() {

},
onShow() {

},
onHide() {

},
 methods: {

}
}
</script>
<style>
</style>

Keywords: uni-app

Added by bcoffin on Thu, 17 Feb 2022 22:33:10 +0200