2017-09-24 372 views
0

我有一個從服務器發送的html塊,我想從嵌入在該html中的鏈接調用方法或函數。Vue.js從動態html調用方法

在我.vue文件,該HTML被顯示,像這樣:

<template> 
<div v-html="myhtml"></div> 
</template> 

<script> 
import axios from 'axios' 
export default { 
    data() { 
    return { 
     myhtml: null 
    } 
    }, 
    created() { 
    this.refreshHTML() 
    }, 
    methods: { 
    refreshHTML() { 
     axios.get()// get my html 
     this.myhtml = response.data 
    }, 
    myFunction() { 
     //do my function stuff here... 
    } 
    } 
} 
</script> 

什麼我想這是牽強的HTML做的是附上觸發我的功能,像這樣一個onclick事件:

<a href="myurl" onclick='event.preventDefault();myFunction(this.href);'>link</a> 

但是當我嘗試,我得到:

ReferenceError: Can't find variable: myFunction

+0

你也可以做這樣的事情:https://codepen.io/Kradek/pen/zEopZd?editors=1010 – Bert

回答

1

這尖叫壞PRACTIC到處都是。

如果我不得不這樣做:

我的功能添加到全球範圍內(不好的做法),並從HTML事件處理程序(也不好的做法)稱之爲:

<template> 
<div v-html="myhtml"></div> 
</template> 

<script> 
import axios from 'axios' 
export default { 
    data() { 
    return { 
     myhtml: null 
    } 
    }, 
    created() { 
    this.refreshHTML(); 
    window.myFunction = this.myFunction.bind(this); 
    }, 
    methods: { 
    refreshHTML() { 
     axios.get()// get my html 
     this.myhtml = response.data 
    }, 
    myFunction() { 
     //do my function stuff here... 
    } 
    } 
} 
</script> 

考慮將html轉換爲vue組件,並改用它們。

+0

謝謝你。順便說一句,我打開這個以不同的方式完成,但這個特定的服務器返回的HTML依賴於調用另一個服務(帶有一個模糊的API密鑰)來獲取其數據,它不能嵌入到應用程序本身。你有另外一個建議嗎?這是我的應用程序中這種類型的東西(看起來)必需的唯一地方。 – Stephen

+0

我想我可以返回組成部分的HTML,然後將點擊處理程序應用於分解模板中的那些處理程序,您認爲這樣會更好嗎? – Stephen

+0

是的,如果你可以將模板加入到你的組件中 - 然後將你的組件方法綁定到dom部件上會好很多(仍然不是最好但更好)。 我甚至會繼續創建一個自定義組件,它接收要下載的html路徑,選擇器和處理程序進行綁定。 – PiniH