本文簡介
點贊 + 關注 + 收藏 = 學會了
在 uni-app 或者 微信小程式 中,都有 web-view 元件。
該元件是一個浏覽器元件,可以承載網頁的内容。而且該元件是全屏的,會覆寫該元件之外的其他内容。
本文要講解在 uni-app 中使用 web-view 怎麼實作大量資料通信。
我所使用的是 Vue 3 文法。
web-view 資料通信方法
web-view 文檔
web-view 其實有點像 iframe ,但在 uni-app 又提供了幾種基礎的通信方式。
基礎用法可以看文檔,本文主要講解如何在 主應用 向 web-view 傳輸資料。
本案例目錄結構
省略部分目錄
- hybrid
|- html
|- js
|- uni.webview.1.5.3.js
|-index.html
- pages
|- index
|- index.vue
父傳子
我們暫定,主應用 為 父,web-view 的頁面為 子 。
“父傳子” 的方式有2種:
- 通過 url 傳值
- 使用 uni.webview.js
1、通過 url 傳值
資料量少的話,可以通過 url 的方式傳給子應用。
index.vue
<template>
<view class="content">
<web-view
src="/hybrid/html/index.html?msg=hello"
></web-view>
</view>
</template>
這種方法的優點是簡單,缺點是傳輸的資料量有限,而且基本傳輸的都是字元串。
2、使用 uni.webview.js 傳值
本文使用的是 uni.webview.1.5.3.js ,在閱讀本文時可能官方已經更新了新版。
你可以在 web-view 文檔 裡,滑到“注意事項”裡面找到最新版的下載下傳位址
主應用 /pages/index/index.vue
<template>
<view class="content">
<web-view
ref="webview"
src="/hybrid/html/index.html"
@message="handleMessage"
></web-view>
</view>
</template>
<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
const webview = ref(null)
const pages = getCurrentPages()
const vw = ref(null)
// 擷取子應用
function getVw() {
// 找到路由棧裡的最後一位
vw.value = pages[pages.length - 1].$getAppWebview().children()[0]
// 使用 evalJS 方法,調用子應用裡的事件
// receiveData 是在子應用裡定義的事件
// 最後需要注意,evalJS 傳入的是一個字元串。
vw.value.evalJS("receiveData({msg: '雷猴啊'})")
}
onLoad(() => {
// 如果是頁面初始化調用時,需要延時一下
setTimeout(() => {
getVw()
}, 1000)
})
</script>
子應用 /hybrid/html/index.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>web-view</title>
</head>
<body>
<!-- 引入 uni.webview.js -->
<script src="./js/uni.webview.1.5.3.js"></script>
<script>
// 接收外層傳進來的資料
function receiveData(data) {
console.log(JSON.stringify(data))
}
</script>
</body>
</html>
這麼簡單就實作了大量資料的傳輸,而且還可以傳對象等資料。
最後需要注意的是,子應用定義接收資料的方法名,要跟主應用調用時一緻。
比如本例定義的方法名為 receiveData 。
子傳父
子應用要向主應用傳值,uni-app 官方就提供了方法 @message 。
主應用 /pages/index/index.vue
<template>
<view class="content">
<web-view
src="/hybrid/html/index.html"
@message="handleMessage"
></web-view>
</view>
</template>
<script setup>
import { ref } from 'vue'
// 接受 webview 傳遞過來的資料
function handleMessage(msg) {
console.log(msg)
}
</script>
子應用 /hybrid/html/index.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>web-view</title>
</head>
<body>
<div>
<button onclick="handleClick()">向上傳遞資料</button>
</div>
<script src="./js/uni.webview.1.5.3.js"></script>
<script>
// 向外傳遞資料,資料要放在data裡
function handleClick () {
uni.postMessage({
data: {
msg: '雷猴'
}
})
}
</script>
</body>
</html>
此時在頁面上點選按鈕,主應用就會接收到子應用傳過來的資料。
除了 @message 外,uni-app 還提供了很多方法和屬性可以調用。