vue中iframe如何引用html文件,以及傳參調(diào)用接口

1. 創(chuàng)建html文件

1. 在public文件中創(chuàng)建static文件夾

2.項(xiàng)目中創(chuàng)建一個(gè)vue 文件來(lái)引入該文件

1. 代碼如下

<iframe :src="src"?style="width:100%;height:100%" ></iframe>

2. data定義數(shù)據(jù),注意 路徑直接用文件夾開(kāi)頭引入

????src: 'static/page.html'

3. vue傳參給html

1. vue組件 iframe 先自定義方法? ? (?v-trigger)

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

2. vue組件自定義觸發(fā)方法: (觸發(fā)methods? ? ?vueSendMsg方法? 將路由參數(shù)傳給html文件)

directives: {

? ? ? ? ? trigger: {

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

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

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

? ? ? ? ? }?

},

3.vue? methods方法如下

methods() {

? ??vueSendMsg() {

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

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

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

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

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

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

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

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

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

},

4. html文件接受vue參數(shù)(event.data即為vue傳給的數(shù)據(jù))

<script>

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

? ? ? ? ? ? function getVueData(event) {

? ? ? ? ? ? ? ? ? ? console.log(event.data)

? ? ? ? ? ? }

</script>

4. vue觸發(fā)html方法? 傳參給vue

1. vue組件button定義

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

methods() {

????htmlFunClick(){

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

? ? ? ? ?window['setThis'] = (message, data) => {?

? ? ? ? ? ?????console.log(message,data)

? ? ? ? ?}

????}

},

2. html文件
<script>

????function?clickfun(event) {

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

? ? ? ? // 此處調(diào)用接口:

? ? ? ? const url = "http:localhost:8080/test/"? ? // 現(xiàn)實(shí)服務(wù)器地址

? ??????$.ajax({

? ? ? ? ? ? ? ? type: "POST"? ??? ? // 請(qǐng)求方式

? ? ? ? ? ? ? ? url: `${url}apiList`,? ??? ? // 請(qǐng)求路徑

? ? ? ? ? ? ? ? headers: {? ???// headers配置

????????????????????????"Content-Type": "application/json; charset=utf-8"

????????????????},??

? ? ? ? ? ? ? ? dataType: "json",?? ? // 數(shù)據(jù)類(lèi)型

? ? ? ? ? ? ? ? data: JSON.stringify({reqBody: "1111"}),?? ? // 入?yún)?/p>

? ? ? ? ? ? ? ? success: function(data) {? ? // 成功后返回

? ? ? ? ? ? ? ? ? ? ? ? console.log(data)

????????????????????????window.parent['setThis']('成功',data)? ? // 傳參給vue文件

????????????????},

? ? ? ? ? ? ? ? error: function(data) {

? ??????????????????????console.log(data)

? ?????????????????????window.parent['setThis']('失敗',data)?

? ? ? ? ? ? ? ? }

????????})

????}

</script>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容