我有一个从服务器发送下来的 html 块,我想从嵌入在该 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>
Run Code Online (Sandbox Code Playgroud)
我想在获取的 html 中附加一个触发我的函数的 onclick 事件,如下所示:
<a href="myurl" onclick='event.preventDefault();myFunction(this.href);'>link</a>
Run Code Online (Sandbox Code Playgroud)
但是当我尝试时,我得到:
参考错误:找不到变量:myFunction
这到处都是糟糕的做法。
如果我必须这样做:
我会将该函数添加到全局范围(不好的做法),并从 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>
Run Code Online (Sandbox Code Playgroud)
考虑将 html 转换为 vue 组件并使用它们。
| 归档时间: |
|
| 查看次数: |
2814 次 |
| 最近记录: |