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>