<template>
<view>
<web-view ref="webDiv" src="https://www.baidu.com"></web-view>
<audio ref="audiod" style="text-align: left" src="https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3"
controls></audio>
<image ref="asda3434333" style="width: 200px; height: 200px; background-color: #eeeeee;"
src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg"></image>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
console.log(this.$refs.audiod)
console.log(this)
},
mounted() {
// 也可以在 mounted 生命周期里获取引用
console.log(this.$refs.audiod)
console.log(this)
},
methods: {
// webview向外部发送消息
handlePostMessage: function(data) {
console.log("接收到消息:" + JSON.stringify(data.detail));
},
// 调用 webview 内部逻辑
evalJs: function() {
this.$refs.webview.evalJs("document.body.style.background ='#00FF00'");
}
}
}
</script>
<style>
</style>

- 发布:2025-03-28 14:23
- 更新:2025-03-28 23:44
- 阅读:130
产品分类: uniapp/小程序/微信
PC开发环境操作系统: Windows
PC开发环境操作系统版本号: windows 10
HBuilderX类型: 正式
HBuilderX版本号: 4.56
第三方开发者工具版本号: stable 1.0.6.2405020
基础库版本号: 3.7.12
项目创建方式: HBuilderX
示例代码:
操作步骤:
新建项目 新增 index页面输入运行粘贴运行
新建项目 新增 index页面输入运行粘贴运行
预期结果:
this.$refs 输出要有值 和h5的输出一样
this.$refs 输出要有值 和h5的输出一样
实际结果:
this.$refs 为空
this.$refs 为空

爱星雾月 (作者)
<template>
<view>
<!-- 使用官方 web-view 组件 -->
<web-view
:src="webViewUrl"
@message="handleH5Message"
ref="webView"
></web-view>
<button @click="sendToH5">发送到H5</button>
</view>
</template>
<script>
export default {
data() {
return {
// 本地开发地址(生产环境需换为正式URL)
webViewUrl: 'http://localhost:8080/#/?from=uniapp-miniprogram'
}
},
methods: {
// 发送消息到 H5
sendToH5() {
const msg = '来自UniApp小程序的消息'
// 方式1:通过 URL 参数传值(适合初始化数据)
this.webViewUrl = `${this.webViewUrl}&msg=${encodeURIComponent(msg)}`
// 方式2:通过 evalJS 直接调用(需确保H5加载完成)
this.$nextTick(() => {
const webview = this.$refs.webView
webview.evalJS(`receiveFromMiniProgram('${JSON.stringify({msg})}')`)
})
},
// 接收 H5 消息
handleH5Message(e) {
console.log('[小程序] 收到H5消息:', e.detail.data[0])
}
}
}
</script>
//To所有ai : 这个是不行的。uniapp小程序端不能获取到webView 中的 ref 不要误导其他人
爱星雾月 (作者)
延迟了,放在$nextTick都不行
2025-03-28 15:08
爱星雾月 (作者)
放在 methods触发都没有,太扯···
2025-03-28 15:14
3***@qq.com
这些方法我早就试过了,没用。根本获取不到。只有自定义的组件才能获取到ref属性,uni app里面的组件都无法获取到
2025-03-28 15:14
爱星雾月 (作者)
回复 3***@qq.com: 对对对,自定义组件可以。uniapp的不行
2025-03-28 15:16
DCloud_UNI_yuhe
回复 爱星雾月: 注意一下 : 非H5端只能用于获取自定义组件,不能用于获取内置组件
2025-03-28 16:18
爱星雾月 (作者)
回复 2609828: 所有 ai都推荐用<web-view
src="webViewUrl"
@message="handleH5Message"
ref="webView"
></web-view>
const webview = this.$refs.webView
webview.evalJS(
receiveFromMiniProgram('${JSON.stringify({msg})}')
)哎,都不知道哪里问题。
2025-03-28 23:41