前言
某業(yè)務(wù)場(chǎng)景需要支持H5跳轉(zhuǎn)微信小程序,查閱官方文檔發(fā)現(xiàn)官方提供了相關(guān)的方案
官方文檔地址:wx-open-launch-weapp
其核心用例為
<wx-open-launch-weapp
id="launch-btn"
username="gh_xxxxxxxx"
path="pages/home/index?user=123&action=abc"
>
<template>
<style>.btn { padding: 12px }</style>
<button class="btn">打開(kāi)小程序</button>
</template>
</wx-open-launch-weapp>
<script>
var btn = document.getElementById('launch-btn');
btn.addEventListener('launch', function (e) {
console.log('success');
});
btn.addEventListener('error', function (e) {
console.log('fail', e.detail);
});
</script>
這里的例子是普通H5的寫法,如果使用了框架品擎,例如Vue六敬,則需要對(duì)wx-open-launch-weapp
內(nèi)的template
進(jìn)行變形
<script type=“text/wxtag-template”>
<style>.btn { padding: 12px }</style>
<button class="btn">打開(kāi)小程序</button>
</script>
疑問(wèn):template標(biāo)簽中btn樣式設(shè)置問(wèn)題
設(shè)置按鈕樣式的時(shí)候發(fā)現(xiàn)百分比寬度不可以碘赖,看到社區(qū)有人說(shuō)在wx-open-launch-weapp
中使用style="display: block; width: 100%"
,然后在標(biāo)簽外部套一層div設(shè)置wrap樣式
遂嘗試,模擬器可以正常展示布局普泡,但是在iPhone X - iOS 14.4的設(shè)備上發(fā)現(xiàn)按鈕的寬度異常播掷,幾個(gè)同事也出現(xiàn)了同樣的問(wèn)題,懷疑是不是百分比寬度的問(wèn)題劫哼,用固定的px可以展示出來(lái)
所以嘗試用flex布局解決叮趴,固定按鈕寬高,然后align-item: center;
結(jié)論
讓按鈕部分定寬高权烧,然后父容器設(shè)置flex
-column
-center
實(shí)現(xiàn)居中即可
<style>
.wrap {
margin: 0 46px;
display: flex;
flex-direction: column;
align-items: center;
}
.img {
width: 100%;
margin: 70px 0 40px;
}
.launch_btn {
width: 230px;
display: block;
}
</style>
<div class="wrap hide">
<img src="xxx.png" class="img" />
<wx-open-launch-weapp class="launch_btn" id="launch-btn" username="" path="">
<template>
<style>
.btn {
box-sizing: border-box;
padding: 12px;
width: 230px;
background-color: #00a4ff;
border-radius: 4px;
color: #fff;
text-align: center;
font-size: 16px;
border: none;
}
</style>
<p class="btn">打開(kāi)小程序</p>
</template>
</wx-open-launch-weapp>
</div>