iframe:vue組件與html文件相互傳參

vue文件

<iframe :src="src"?ref="iframe"?style="width:100%;height:100%" @click="vueSendMsg"?v-trigger></?iframe>

<button @click="htmlFunClick">觸發(fā)html方法</button>


?// 自定義方法傳參準(zhǔn)備

directives: {

? ??????trigger: {??

? ? ? ? ? ? ? ? ? ? ?inserted (el, pinging) {

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? el.click()

? ? ? ? ? ? ? ? ? ? ?}

? ? ? ? ? }?

},

methods() {

? ? ? // 觸發(fā)方法 傳參給html文件

? ??????vueSendMsg() {

? ? ????????setTimeout(() =>{

????????????????????const iframeWindow =?this.$refs.iframe.contentWindow

????????????????????iframeWindow.postMessage({

????????????????????????????cmd: 'myVue',

? ? ? ? ? ? ? ? ? ? ? ? ? ? ?params: {

????????????????????????????????????id: this.$route.query.id

????????????????????????????}

????????????????????}, '*')

????????}, 1000),


? ?????htmlFunClick(){

? ???????????????this.$refs.iframe.contentWindow.clickfun()? ? ?// 觸發(fā)html定義的clickfun方法

? ??????????????window['setThis'] = (message, data) => {? // 接受html傳過來的參數(shù)

? ??????????????????????console.log(message, data)? ? //? ?console ----->?'觸發(fā)成功', '1234'

? ? ? ? ?? ??????}

????????}

},

html文件

<script>

? // 準(zhǔn)備接受vue 傳給的參數(shù)

????window.addEventListener("message",?getVueData)

????function?getVueData(event) {

????????????console.log(event.data)? //?vue 傳給的參數(shù)

? ? }

?????function?clickfun(event) {?

? ??????????console.log("html方法被觸發(fā)啦!")

? ??????????window.parent['setThis']('觸發(fā)成功', '1234')? ? // 傳參給vue文件

????}

</script>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容