uni-app 与 renderjs 通信指南
在 uni-app 开发中,renderjs 是一种运行在视图层的 JavaScript 模块,适用于处理高性能渲染和直接操作 DOM 的场景。
一、页面与 renderjs 模块通信
1. 页面监听变量变化
在页面的 <view> 组件中,通过 :change 指令监听变量 operation 的变化,当该变量发生变化时,自动调用 renderjs 模块中的 loadOperation 方法。
<view :operation="operation" :change:operation="test.loadOperation">test模块:{{ test.clicked }}</view>
2. renderjs 模块响应变化
在 renderjs 模块中定义 loadOperation 方法,用于接收页面传递的新值,并更新模块内部状态。
loadOperation(newValue, oldValue, ownerInstance, instance) {this.clicked = newValue; // 更新内部状态this.sendMsg(); // 向页面发送消息}
二、renderjs 向页面发送数据
1. 调用页面方法
在 renderjs 中,通过 this.$ownerInstance.callMethod 调用页面定义的 reciveMessage 方法,将数据传回页面。
sendMsg() {this.$ownerInstance.callMethod('reciveMessage', ++this.count);}
2. 页面接收数据
在页面的 methods 中定义 reciveMessage 方法,用于接收 renderjs 传来的数据。3
reciveMessage(data) {this.total = data;}
三、完整代码示例
页面部分(.vue)
<template><view><view:operation="operation":change:operation="test.loadOperation">test模块:{{ test.clicked }}</view><br /><view>您总共点击了 {{ total }} 次</view><br /><button @click="onClick">点击</button></view></template><script>export default {data() {return {operation: null,total: 0};},methods: {onClick() {this.operation = !this.operation;},reciveMessage(data) {this.total = data;}}};</script><scriptmodule="test"lang="renderjs">export default {data() {return {clicked: false,count: 0};},methods: {loadOperation(newValue, oldValue, ownerInstance, instance) {this.clicked = newValue;this.sendMsg();},sendMsg() {this.$ownerInstance.callMethod('reciveMessage', ++this.count);}}};</script><style>/* 样式部分可根据需要添加 */</style>
四、注意事项
-
renderjs运行在视图层,无法直接访问页面的data或methods,需通过:change和callMethod实现通信。 -
适用于需要高性能渲染或直接操作 DOM 的场景,如图表、地图等。
-
仅支持 app-vue 和 H5 端,小程序端不支持。
夜雨聆风