一.父页面向子页面传值

parent.vue

<template>
    <iframe id="iframe" width="100%" :src="src"></iframe>
</template>
<script>
export default {
	data() {
        return {
            iframe: null,
            src: '', //需要加载的子页面url
        }
    },
    async mounted(){
	    var that = this
	    this.iframe = document.getElementById('iframe')
	    this.iframe.onload = function(){
	        // iframe加载完成后要进行的操作
	        that.postMsg()
	    }  
		// if (iframe.attachEvent){ // 兼容IE写法
        //     iframe.attachEvent("onload", function(){
        //         // iframe加载完成后要进行的操作
        //         postMsg()
        //     })
        // } else {
        //     iframe.onload = function(){
        //         // iframe加载完成后要进行的操作
        //         postMsg()
        //     }
        // }
	},
	methods: {
        async postMsg() {
        	//将token传递给子页面
            let token = await this.$user.getToken()
            let param = {
                token
            }
          	this.iframe.contentWindow.postMessage(param,'*')
        },
    }
}

子页面

var token = ''

window.addEventListener('message', function(e) {
  	console.log(e.data)
    token = e.data.token
    //执行其他操作
})

二.子页面向父页面传值

子页面

<button id="admin-btn">传值</button>
$("#admin-btn").on('click', function(){
   event.stopPropagation()
    let info = {
        msg: '我是子页面'
    }
    window.parent.postMessage(info, '*');
})

parent.vue

created() {
    var that = this
    // 接收子页面传送的数据
    window.addEventListener('message', function (e) {
        var data = e.data;
        console.log(data.msg) //我是子页面
        //执行其他操作
    });
},

三.iframe 高度自适应

created() {
   var that = this
    window.addEventListener('resize', function (e) {
        const deviceHeight = document.documentElement.clientHeight;
        this.iframe.style.height = deviceHeight+ 'px'; //数字是页面布局高度差
    });
},
async mounted(){
    var that = this
    this.iframe = document.getElementById('iframe')
    const deviceHeight = document.documentElement.clientHeight;
    this.iframe.style.height = deviceHeight+ 'px'; //数字是页面布局高度差
},
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐