当前位置:网站首页>Advanced cross platform application development (II): uni app practice
Advanced cross platform application development (II): uni app practice
2022-07-01 05:39:00 【No Silver Bullet】
List of articles
One 、 Preface
In the early post 《 Advanced cross platform application development ( One ) approach uni-app》 in , Explained the use of uni-app Basic knowledge of cross end development of framework , This blog post mainly explains uni-app Actual combat process and knowledge points involved .
Two 、 Project practice
2.1 Style framework
uni-ui The extension component complies with easycom Component specifications , It can be directly applied to .
If the component does not meet easycom standard , You need to manually... In the code import And register components , And then you can use it .
standard js and browser js The difference between
uni-appOfjsCode ,h5The client runs in the browser . Noth5End ( Contains applets andApp),AndroidThe platform runs onv8 enginein ,iOSThe platform runs oniOSSelf containedjscoreIn the engine , Are not running in the browser orwebviewin .Not
H5End , Though not in favor ofwindow、document、navigatorAnd so onjs API, But it also supports standardsECMAScript.Don't put the browser's
jsExtension object is equivalent to standardjs.
uni-appNon -H5End , Support standards as welljs, Supportif、forEqual grammar , Support string 、 Numbers 、 Time 、 Boolean value 、 Array 、 Custom object and other variable types and various processing methods . It just doesn't supportwindow、document、navigatorBrowser specific objects such as .
2.2 Routing jump
uni.navigateTo(OBJECT)
Keep the current page , Jump to a page in the app , Useuni.navigateBackYou can go back to the original page .
Be careful ️:
- The page Jump path has hierarchical restrictions , You can't jump to new pages without restrictions ;
- Jump to
tabBarThe page can only useswitchTabJump ;- route
APIThe target page must be inpages.jsonRegistered invuepage . If you want to openweb url, stayAppThe platform can useplus.runtime.openURLorweb-viewComponents ;H5 Platform usewindow.open; The applet platform usesweb-viewComponents (url Need to be in the applet's online white list ). stayhello uni-appThere are components inulink.vueMultiple terminals have been encapsulated , May refer to .APP-NVUEThe platform does not supportthis.getOpenerEventChannel()How to geteventChannel, Please change itthis.$scope.eventChannelTo get , Please refer to the above example for details .
uni.navigateBack(OBJECT)
Close current page , Go back to the previous page or multi-level page . It can be done by getCurrentPages()Get the current page stack , Decide how many layers you need to go back .uni.redirectTo(OBJECT)
Close current page , Jump to a page in the app .uni.reLaunch(OBJECT)
Close all pages , Open to a page in the app .
Be careful ️:
If called
uni.preloadPage(OBJECT)Will not close , Just trigger the lifecycleonHide.H5 End calls
uni.reLaunchAfter that, the page stack will be destroyed , But you can't empty the history before the browser , herenavigateBackCan't return , If there is a history, click the browser's back button or callhistory.back()You can still navigate to other browser history .
uni.switchTab(OBJECT)
Jump totabBarpage , And shut down all the otherstabBarpage .
2.3 Request backstage
- In the catalog
serviceSo let's make a new onerequest.jsfile , encapsulate .
mport {
baseURL
} from './config.js'
import {
getToken,
goToLogin
} from '@/common/util.js'
const setToken = (res) => {
if (res.hasOwnProperty("access_token")) {
getApp().globalData.token = getToken(res.token_type, res.access_token)
console.log('token info is: ', getApp().globalData.token)
}
if (res.hasOwnProperty('msg')) {
if (res.msg === ' User credentials have expired ') {
goToLogin()
}
}
};
const handleErr = (err) => {
uni.hideLoading()
uni.showModal({
title: ' Tips ',
content: err.errMsg,
showCancel: false,
success: function(res) {
if (res.confirm) {
// console.log(' The user clicks ok ');
} else if (res.cancel) {
// console.log(' The user clicks cancel ');
}
}
});
};
const request = (url, params, method, tips) => {
uni.showLoading({
title: tips || " Loading ..."
})
const curUrl = (url.indexOf('http') !== -1 || url.indexOf('https') !== -1) ? url : baseURL + url
console.log('The request url info is: ', curUrl)
console.log('The request params info is: ', params)
return new Promise((resolve, reject) => {
uni.request({
url: curUrl,
method: method || "POST",
header: {
'Content-Type': 'application/json',
'Authorization': getApp().globalData.token || 'Basic YXBwOmFwcA=='
},
data: params || {
},
success(res) {
setToken(res.data)
resolve(res.data)
console.log('The request success return info is: ', res.data)
},
fail(err) {
reject(err)
console.log('The request fail return info is: ', err)
},
complete() {
uni.hideLoading()
}
})
}).catch(err => {
handleErr(err)
})
};
export {
requestForm,
requestJSON
}
- stay
commonCreate a folder togetherutils.jsFiles are used to gettoken.
// obtain token
export function getToken(token_type, access_token) {
let token = token_type.charAt(0).toUpperCase() + token_type.slice(1) + ' ' + access_token;
return token;
}
// Model Prompt whether to return to the login page
export function goToLogin() {
uni.showModal({
title: ' reminder ',
content: " You haven't signed in yet , Please log in ",
success: function(res) {
if (res.confirm) {
// console.log(' The user clicks ok ');
uni.navigateTo({
url: '/pages/ucenter/userinfo/userinfo'
})
} else if (res.cancel) {
// console.log(' The user clicks cancel ');
}
}
})
}
- Create a new one
apiCatalog , Then correspondingpagesCreate a directory and file with the corresponding name on the page ,list.jsA file is a request interface .
// Introduce tool classes
import request from '@/service/request.js'
export function get(data){
//
return request({
url: '/forshop/getprefer',
method: 'GET',
contentType:'application/x-www-form-urlencoded',
data: data
})
}
Be careful ️:
uni.requestIf no incomingsuccess / fail / completeParameters , Will return encapsulated by defaultPromiseobject .
- Then on the page
list.vueCall interface .
<script>
import {
get } from "@/api/list/list"
export default {
methods: {
get().then(res => {
console.log(res)
}).catch (err => {
console.log(err)
})
}
}
</script>
The above is promise Form of interface request .await The interface request mode of form is :
import {
get } from "@/api/list/list"
// Await
async function request () {
var [err, res] = await get({
url: 'https://www.example.com/request'
});
console.log(res.data);
}
2.4 uni-app https Request mode
Conventional HTTP There are the following security issues :
Communicate in clear text , Content may be bugged ;
Do not verify the identity of the communicating party , The identity of the communication party may be disguised ;
Can't prove the integrity of the message , The message may be tampered with .
To solve the problem of secure communication ,HTTPS emerge as the times require . Actually ,HTTPS It's not a new agreement , But standing HTTP On my shoulder , Give Way HTTP The first and SSL(Secure Sockets Layer) signal communication , Again by SSL and TCP signal communication , in other words HTTPS Communication using tunnels . By using SSL,HTTPS Possess encryption ( Anti wiretapping )、 authentication ( Anti camouflage ) and Integrity protection ( tamper-proof ).
2.4.1 encryption
(1) Symmetric key encryption (Symmetric-Key Encryption), Encryption and decryption use the same key .
(2) Asymmetric key encryption , Also known as public key encryption (Public-Key Encryption), Encryption and decryption use different keys .
The public key is available to all , After the communication sender obtains the public key of the receiver , You can use the public key to encrypt , After receiving the communication content, the receiver uses the private key to decrypt . Asymmetric keys are used for encryption , It can also be used to sign . Because private key can't be obtained by others , Therefore, the communication sender uses its private key To sign , The receiver decrypts the signature with the sender's public key , We can judge whether the signature is correct .
HTTPS Using mixed encryption mechanism , Use Asymmetric key Encryption is used for transmission Symmetric key To ensure the security of the transmission process , Then use Symmetric key Encrypt the communication to ensure the efficiency of the communication process .
2.4.2 authentication
Authenticate the communicating party by using a certificate .
Digital certificate authority (CA,Certificate Authority) It is a third-party organization that both client and server can trust . The operator of the server asked CA Apply for a public key ,CA After identifying the applicant , Will do digital signature to the applied public key , Then distribute the signed public key , And put the public key into the public key certificate and bind it together . Conduct HTTPS When communication , The server will send the certificate to the client . After the client obtains the public key , First use digital signature for verification , If the verification passes , You can start communicating .
2.4.3 Integrity protection
SSL Provide message digest function for integrity protection . HTTP Also provided MD5 Message summary function , But it's not safe . For example, after the message content has been tampered with , And recalculate MD5 Value , The communication receiver is not aware of the tampering .
HTTPS The message digest function of is secure , Because it combines encryption and authentication These two operations . Just imagine , Encrypted message , After being tampered with , It's also hard to recalculate message digest , Because it's not easy to get plaintext .
2.4.4 HTTPS The shortcomings of
Because of the need for encryption and decryption , So it's going to be slower ;
A high fee for Certificate Authorization is required .
uni-app application https Request mode , Need to cooperate with SSL certificate :
If it is HTTPS Access Certificate , It should be the server configuration , When the front end initiates a request , The address is written as https The prefix is enough , for example :https://www.example.com/login
2.5 Application planning 、 Configuration and adjustment
It's not that there's SSL The certificate will be all right , Also consider the use in the application , Need to plan 、 Server configuration 、 Application adjustment and other links .
because SSL Than http It takes more cpu resources ( Mainly in the phase of establishing handshake connection , Then encrypt the content ), So for general websites , Only some places need to use https, Most open content is unnecessary , Depending on your business requirements . For example, for many websites with low security requirements , Not at all https It is also acceptable .
Some pages support both http and https , Or just support https、 mandatory https?
At the same time, support means that users can access it with any protocol , Then the user's request is mainly guided by the link of the page itself , Because ordinary users will not modify the address bar on their own .
Generally, our website can support http and https, All accessible . But it's easy to have the problem of mixed content or mixed script .
It can also be planned to support some pages https, Generally, public pages don't need https, Just change the links in some places to https That's all right. . Specifically expect to https In the page visited , The absolute of reference URL Can be used explicitly https link .
Forced or not https ? For websites with high security or some pages in the website , Can be forced to use https visit , Even if users manually put... In the address bar https Change it to http, Will also be automatically redirected back to https On . For example, you can configure web The server rewrite The rules put these http url Automatically redirect to the corresponding https url On ( This makes maintenance easier ), Without changing the application .
2.6 Application market on the shelf
application HBuilder When the cloud packs , Prompt the following verification information :
among , The main tip is “ The current app lacks relevant configuration ”, The following measures can be taken to solve :
open HBuilder Project manifest.json file , Switch to “ Source view ” term
uni-app project
stay “app-plus” -> “privacy” Add under node prompt node .
5+ App project
stay “plus” -> “privacy” Add under node prompt node .
promptString type , Required , Privacy policy prompt box configuration policy , Value fortemplate、custom、none, The default value isnone.templateUse the native prompt box template , Customizable title 、 The content has the text on the button .customCustomize privacy policy prompt box ,uni-appIt is recommended to usenvueCustomize the page ,5+ APPUsehtmlCustomize the page .noneDo not pop up the privacy policy prompt boxtemplatejson Format , Optional , What is displayed on the template prompt box
"privacy": {
"prompt": "template",
"template": {
"title": " Service agreement and privacy policy ",
"message": " Please read carefully 、 Full understanding “ The service agreement ” and “ Privacy policy ” Articles , Including but not limited to : In order to better serve you , We need to collect your device identification 、 Operation logs and other information are used for analysis 、 Optimize application performance .<br/> You can read <a href="">《 The service agreement 》</a> and <a href="">《 Privacy policy 》</a> Learn more . If you agree to , Please click the button below to start accepting our service .",
"buttonAccept": " I got it! ",
"buttonRefuse": " Disagree for the time being "
}
}
3、 ... and 、 Expanding reading
边栏推荐
- 数字金额加逗号;js给数字加三位一逗号间隔的两种方法;js数据格式化
- 实战:redux的基本使用
- Typeorm framework
- Deeply understand the underlying implementation principle of countdownlatch in concurrent programming
- JDBC common interview questions
- 轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷
- Cockroachdb: the resistant geo distributed SQL database paper reading notes
- 【考研高数 自用】高数第一章基础阶段思维导图
- Txncoordsender of cockroachdb distributed transaction source code analysis
- Unity项目心得总结
猜你喜欢

JDBC common interview questions

小程序常用组件小结

【考研高数 自用】高数第一章基础阶段思维导图

Basic electrician knowledge 100 questions

Txncoordsender of cockroachdb distributed transaction source code analysis

数字金额加逗号;js给数字加三位一逗号间隔的两种方法;js数据格式化
![[RootersCTF2019]babyWeb](/img/b4/aa8f8e107a9dacbace72d4717b1834.png)
[RootersCTF2019]babyWeb

el-form表单新增表单项动态校验;el-form校验动态表单v-if不生效;

Use and principle of wait notify

0xc000007b应用程序无法正常启动解决方案(亲测有效)
随机推荐
Use and principle of wait notify
Tar command
从MLPerf谈起:如何引领AI加速器的下一波浪潮
mysql 将毫秒数转为时间字符串
Unity uses SQLite
One click deployment of highly available emqx clusters in rainbow
A little assistant for teenagers' physiological health knowledge based on wechat applet (free source code + project introduction + operation introduction + operation screenshot + Thesis)
Mongodb learning chapter: introduction after installation lesson 1
2022.6.30-----leetcode.1175
RecycleView的一些使用
【考研高数 自用】高数第一章基础阶段思维导图
Txncoordsender of cockroachdb distributed transaction source code analysis
Leetcode top 100 questions 1 Sum of two numbers
在Rainbond中一键部署高可用 EMQX 集群
LRU cache for leveldb source code analysis
Data governance: data governance management (Part V)
rust猜数字游戏
HDU - 1024 Max Sum Plus Plus(DP)
0xc000007b应用程序无法正常启动解决方案(亲测有效)
Vscode function annotation / file header annotation shortcut