微信小程序+Taro 混编,Taro 使用微信原生 behaviors

最近有一个小程序项目,因为一些原因项目架构选择了微信小程序原生+Taro 混编的方式进行开发,在开发的过程中发现 Taro 不支持使用原生的 behaviors 特性,因为混编的原因项目当中已有原生页面在使用 behaviors,所以需要一个方案在不影响其他页面的基础上使 Taro 也能使用这一特性。

behaviors 除了有类似 Mix 的效果,还有生命周期的封装性。所以咱们考虑的方向就是实现这两点就可以了。

最终以挂载一个空的原生组件(它使用了 behaviors)到 Taro 页面做为中转的方式解决了这一棘手的问题。通过中转组件就可以在 Taro 页面调用到 behaviors 的方法,以及使用 behaviors 生命周期的封装。

switchAccountBehaviors.js:

objectivec 复制代码
export default Behavior({
	pageLifetimes: {
        show: function () {
            this.judgeSwitchAccountRefresh();
        }
    },
	methods: {
		const judgeSwitchAccountRefresh = () => {
			// do...
		},
		const doSome = () => {
			// do...
		}
	}
});

wxml 为空的中转组件,路径:@/behaviors/components

objectivec 复制代码
import switchAccountBehaviors from "@/behaviors/switchAccountBehaviors";

Component({
    properties: {},
    data: {},
    behaviors: [switchAccountBehaviors],
    methods: {}
});

Taro 页面的 index.config.js:

objectivec 复制代码
export default ({
  usingComponents: {
    // 定义需要引入的第三方组件
    // 1. key 值指定第三方组件名字,以小写开头
    // 2. value 值指定第三方组件 js 文件的相对路径
    "behaviors-component": "@/behaviors/components",
  }
});

Taro 页面的 index.jsx

objectivec 复制代码
// Taro 页面调用 behaviors 的方法
getCurrentInstance()?.selectComponent("#behaviors-component")?.doSome();

render() {
	...
	return (
		<>
			...
			<behaviors-component id="behaviors-component" /> 
		</>
	)
}
相关推荐
本人手速666+10 分钟前
WeComApi 适合哪些企业微信二次开发场景?从外部群、自动回复到 CRM 对接
微信·企业微信·企微外部群开发·wecomapi·企业微信二次开发
iPad协议个微协议17 小时前
# 微信自动营销系统如何基于 WechatApi 做事件驱动设计
android·微信·企业微信·个人开发·wechatapi·微信个人号开发
软擎19 小时前
微信聊天记录怎么导出给AI分析?用它仅需4步,即可导出PDF、HTML、Excel三种格式,轻松导出所有聊天记录做AI分析
微信·聊天记录导出工具·轻虾导出助手
微笑的曙光21 小时前
第一期 · 本地优先 MVP:不写一个后端,如何做出完整体验
微信小程序
本人手速666+1 天前
企业微信 API 接入层如何降低业务系统复杂度
运维·网络协议·微信·自动化·ipad
EatFan1 天前
Java接入微信支付保姆式教程(三):SpringBoot 接入微信支付并完成统一下单
微信小程序·微信支付·springboot
本人手速666+1 天前
企业微信二次开发中的事件驱动架构:如何把外部事件变成内部流程
微信·自动化·企业微信·个人开发·微信开放平台
xiezhr1 天前
微信里多了个[小微],可以帮你看朋友圈、发消息、点外卖了
微信·aigc·agent
QQ_21696290961 天前
基于SpringBoot+Vue的小生活平台的设计与实现
java·数据库·vue.js·spring boot·spring·微信小程序·生活