vue中iframe嵌套页面传值
时间: 2023-09-24 16:13:53 浏览: 73
在Vue中,如果需要在iframe嵌套页面之间传值,可以使用window.postMessage()方法。
例如,父页面中有一个iframe:
```html
<iframe src="https://example.com"></iframe>
```
在父页面中定义一个方法,用于向iframe发送数据:
```javascript
function sendMessage(data) {
const iframe = document.querySelector('iframe');
iframe.contentWindow.postMessage(data, 'https://example.com');
}
```
在iframe中定义一个事件监听器,用于接收来自父页面的数据:
```javascript
window.addEventListener('message', (event) => {
if (event.origin !== 'https://example.com') return;
const data = event.data;
// 处理接收到的数据
});
```
在接收到数据后,可以在iframe中进行相应的处理。注意要判断消息来源的origin,确保数据来自正确的页面。
相关问题
vue中iframe嵌套页面跳转
在Vue中嵌套iframe页面跳转,可以使用iframe的window对象的location属性进行页面跳转。
例如,在Vue组件中嵌套一个iframe:
```
<template>
<div>
<iframe ref="myIframe" src="http://www.example.com"></iframe>
</div>
</template>
```
然后,在Vue组件的方法中使用iframe的window对象的location属性进行页面跳转:
```
<script>
export default {
methods: {
goToPage() {
this.$refs.myIframe.contentWindow.location.href = 'http://www.example.com/newpage';
}
}
}
</script>
```
在这个例子中,当调用goToPage方法时,会将iframe中的页面跳转到http://www.example.com/newpage。
vue中iframe如何传值
在Vue中,可以通过监听`message`事件来获取并处理从`iframe`传递过来的数据。具体实现方法如下:
```javascript
mounted() {
// 获取并监听iframe传递来的数据
let that = this;
window.addEventListener('message', function (e) {
var res = e.data;
console.log(res, 'iframe传递过来的数据');
// 在这里处理从iframe传递过来的数据
})
}
```
而在`iframe`中,可以通过`window.parent.postMessage()`方法向父窗口传递数据。具体实现方法如下:
```javascript
// 向父窗口传递数据
window.parent.postMessage(obj, '*');
// 如果js外面还有一层js,
// window.parent.window.parent.postMessage(obj, '*');
```