遇到个难题需要跨域刷新iframe,用 postMessage 传递数据解决 方法类似与 vue 父子组件传值 解决方法如下:
一:vue3方式
setup(){
const appIframeReload = () => {
const frame = document.getElementsById('iframe');
setTimeout(() => {
frame.contentWindow.postMessage(200, "*")
}
}, 300)
}
return {
appIframeReload
};
}
mounted(){
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', dealMessage, false);
} else if (typeof window.attachEvent != 'undefined') {
window.attachEvent('onmessage', dealMessage);
}
function dealMessage (e) {
if (e.data == 200) {
e.currentTarget.window.location.reload()
}
}
}
}
二:vue2方式
methods:{
appIframeReload () {
const frame = document.getElementsById('iframe');
setTimeout(() => {
frame.contentWindow.postMessage(200, "*")
}
}, 300)
}
}
mounted()
{
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', dealMessage, false);
} else if (typeof window.attachEvent != 'undefined') {
window.attachEvent('onmessage', dealMessage);
}
function dealMessage (e) {
if (e.data == 200) {
e.currentTarget.window.location.reload()
}
}
}
|