uni-app webview URL 动态绑定无效
uni-app webview URL 动态绑定无效
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | win11 | HBuilderX |
示例代码:
<template>
<view>
<web-view src="webUrl"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
webUrl: '',
}
},
onLoad() {
this.webUrl = 'https://www.qq.com';
},
methods: {
}
}
</script>
<style>
</style>
操作步骤:
- onload方法里 赋值webview的URL 没有效果
预期结果:
- 显示网页
实际结果:
- 空白显示
2 回复
刚试了,没问题 <template>
<web-view :src="webUrl"></web-view>
</template>
<script>
export default {
data() {
return {
webUrl: '',
}
},
onLoad() {
this.webUrl = 'https://ask.dcloud.net.cn/question/186146';
},
methods: {
}
}
</script>在 uni-app 中,使用 webview
组件时,动态绑定 URL 可能会遇到无效的情况。这通常是由于 webview
组件的特性和 uni-app 的生命周期管理机制导致的。以下是一些可能的原因和解决方案:
1. webview
组件的特性
webview
组件在加载时会使用初始的 src
属性值,如果后续动态修改 src
,webview
可能不会自动重新加载新的 URL。
2. 生命周期问题
如果 webview
的 src
是在组件的 mounted
或 created
钩子中动态设置的,可能会导致 webview
没有正确加载新的 URL。
解决方案
方案 1: 使用 v-if
强制重新渲染
可以通过 v-if
控制 webview
的渲染,当 URL 发生变化时,先销毁 webview
,然后再重新创建。
<template>
<view>
<webview v-if="url" :src="url"></webview>
</view>
</template>
<script>
export default {
data() {
return {
url: ''
};
},
mounted() {
// 动态设置 URL
setTimeout(() => {
this.url = 'https://example.com';
}, 1000);
}
};
</script>
方案 2: 使用 key
强制重新渲染
通过给 webview
组件添加 key
属性,当 key
发生变化时,webview
会重新渲染。
<template>
<view>
<webview :src="url" :key="url"></webview>
</view>
</template>
<script>
export default {
data() {
return {
url: ''
};
},
mounted() {
// 动态设置 URL
setTimeout(() => {
this.url = 'https://example.com';
}, 1000);
}
};
</script>
方案 3: 使用 uni.navigateTo
跳转到新的 webview
如果需要动态加载不同的 URL,可以考虑使用 uni.navigateTo
跳转到新的页面,并在新页面中加载 webview
。
uni.navigateTo({
url: '/pages/webview/webview?url=' + encodeURIComponent('https://example.com')
});
在 webview
页面中:
<template>
<view>
<webview :src="url"></webview>
</view>
</template>
<script>
export default {
data() {
return {
url: ''
};
},
onLoad(options) {
this.url = decodeURIComponent(options.url);
}
};
</script>