[英]Vue.js call method from dynamic html
I have a block of html that is sent down from the server, and I want to call a method or function from links embedded in that html.我有一个从服务器发送下来的 html 块,我想从嵌入在该 html 中的链接调用方法或函数。
in my .vue
file, the html is being displayed like so:在我的.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>
And what I would like to do in the html that is fetched is attach an onclick event that fires my function like so:我想在获取的 html 中附加一个触发我的函数的 onclick 事件,如下所示:
<a href="myurl" onclick='event.preventDefault();myFunction(this.href);'>link</a>
But when I try, I get:但是当我尝试时,我得到:
ReferenceError: Can't find variable: myFunction参考错误:找不到变量:myFunction
This screams bad practice all over the place.这到处都是糟糕的做法。
If I HAD to do this:如果我必须这样做:
I'd add the function to the global scope (bad practice), and call it from the html event handler (also bad practice):我会将该函数添加到全局范围(不好的做法),并从 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>
Consider converting the html into vue components and use them instead.考虑将 html 转换为 vue 组件并使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.