最近有一個小程序項目,因為一些原因項目架構(gòu)選擇了微信小程序原生+Taro 混編的方式進行開發(fā),在開發(fā)的過程中發(fā)現(xiàn) Taro 不支持使用原生的 behaviors 特性,因為混編的原因項目當(dāng)中已有原生頁面在使用 behaviors,所以需要一個方案在不影響其他頁面的基礎(chǔ)上使 Taro 也能使用這一特性。
behaviors 除了有類似 Mix 的效果,還有生命周期的封裝性。所以咱們考慮的方向就是實現(xiàn)這兩點就可以了。
最終以掛載一個空的原生組件(它使用了 behaviors)到 Taro 頁面做為中轉(zhuǎn)的方式解決了這一棘手的問題。通過中轉(zhuǎn)組件就可以在 Taro 頁面調(diào)用到 behaviors 的方法,以及使用 behaviors 生命周期的封裝。
switchAccountBehaviors.js:
export default Behavior({
pageLifetimes: {
show: function () {
this.judgeSwitchAccountRefresh();
}
},
methods: {
const judgeSwitchAccountRefresh = () => {
// do...
},
const doSome = () => {
// do...
}
}
});
wxml 為空的中轉(zhuǎn)組件,路徑:@/behaviors/components
import switchAccountBehaviors from "@/behaviors/switchAccountBehaviors";
Component({
properties: {},
data: {},
behaviors: [switchAccountBehaviors],
methods: {}
});
Taro 頁面的 index.config.js:文章來源:http://www.zghlxwxcb.cn/news/detail-677601.html
export default ({
usingComponents: {
// 定義需要引入的第三方組件
// 1. key 值指定第三方組件名字,以小寫開頭
// 2. value 值指定第三方組件 js 文件的相對路徑
"behaviors-component": "@/behaviors/components",
}
});
Taro 頁面的 index.jsx文章來源地址http://www.zghlxwxcb.cn/news/detail-677601.html
// Taro 頁面調(diào)用 behaviors 的方法
getCurrentInstance()?.selectComponent("#behaviors-component")?.doSome();
render() {
...
return (
<>
...
<behaviors-component id="behaviors-component" />
</>
)
}
到了這里,關(guān)于微信小程序+Taro 混編,Taro 使用微信原生 behaviors的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!