uniapp APP端页面触发调用uniapp开发的webview里的方法

原理:

使用 getCurrentInstance() 获取当前组件的 Vue 实例,通过 instance.proxy.$scope.$getAppWebview() 获取 Uniapp 的原生 WebView 对象。 使用 WebView 提供的 evalJS 方法,执行嵌入 H5 页面内的 JavaScript 代码

function getData() {
		url.value = "http://192.168.0.22:5174/#/pages/orderDatelis/orderDatelis"
		orderDetails({
			id: orderId.value
		}).then(res => {
			const {
				end_latitude,
				end_longitude,
				id,
				start_latitude,
				start_longitude
			} = res.data
			send(res.data)
		})
	}

	function send(data) {
		const json = JSON.stringify(data)
		if (instance) {
			const currentWebview = instance.proxy.$scope?.$getAppWebview();
			const wv = currentWebview.children()[0];
			wv.evalJS(`msgFromUniapp(${json})`);
			console.warn("发送");
		} else {
			console.warn('getCurrentInstance() returned null');
		}
	}

代码大意:调完接口后将接口返回参数注入webview

uniapp H5 webview部分:

onMounted(() => {
		window.msgFromUniapp = (res) => {
			send(res)
			try {
				data.value = res
				initMap()
			} catch (e) {
				uni.showToast({
					title: e.message
				})
				send(e.message)
			}

		}
	})

你可能感兴趣的:(uniapp分享,uni-app)