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>