前言

众所周知,uniapp开发APP时是没有window和documen的,那么当我们想要操作dom时,怎么办呢?renderjs通讯就是解决这个问题的。下面开始如何进行renderjs通讯,可以参考uniapp的Renderjs文档以及renderjs示例

代码及解说

:prop是逻辑层向视图层传递的数据,当该数据发生变化时,触发视图层的updateEcharts函数

注意:prop是自定义属性,且 prop要与:change:prop的prop一致,否则无效

echarts.updateEcharts中echarts是视图层<script module="echarts" lang="renderjs">的module的值

echarts需要在视图层操作,所以可以将option传入到视图层

视图层传递消息看postMessage方法

// template内容
<!-- #ifdef APP-PLUS || H5 -->
<view :prop="options" :change:prop="echarts.updateEcharts" id="echarts" class="echarts"> </view>
<!-- #endif -->
// 逻辑层(setup方法)
<script>
export default{
    methods:{
        onMessage(data){
            console.log(data,'视图层向逻辑层发送的数据,注意是个对象');
        }
    }
}
</script>
// 视图层
<script module="echarts" lang="renderjs">
	export default {
		mounted() {
			console.log("渲染层挂载");
		},
		methods: {
			// newValue:新的值
			// oldValue:旧的值
			// ownerInstance:当前组件实例
			// instance:当前实例
			updateEcharts(newValue, oldValue, ownerInstance, instance) {
				this.options = newValue;
			},
			postMessage() {
				// 视图层向逻辑层发送消息
				this.$ownerInstance.callMethod("onMessage", { data: "需要发送的数据" });
			},
		},
	};
</script>

更多推荐