2024年04月19日 建站教程
js如何实现两个iframe之间传值,下面web建站小编给大家详细介绍一下具体实现代码!
父组件传参
<template>
<view>
<iframe :src="/static`/demoA?$[params]`"></iframe>
</view>
</template>
<script>
export default {
data() {
return {
params: ''
};
},
mounted() {
const params = {
name: 'web建站',
age: '3',
}
this.params = encodeURIComponent(JSON.stringify(params))
window.addEventListener('message', this.handleMessage)
},
methods: {
handleMessage(event) {
console.log(event, '事件')
if(event.data.status === 'ok') {
console.log(event.data.params, '参数值')
}
}
}
}
</script>
子组件接收参数
<template>
<view>
<p>demoA发来的参数:{{params}}</p>
<button @click="sendMess">发送数据</button>
</view>
</template>
<script>
export default {
data() {
return {
params: ''
};
},
created() {
const params = JSON.parse(decodeURIComponent(window.location.hash.split('?')[1]))
this.params = params
},
methods: {
sendMess() {
window.parent.postMessage({
status: 'ok',
params: {
id: 12
}
}, '*');
}
}
}
</script>
本文链接:http://so.lmcjl.com/news/2590/