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.
in my .vue
file, the html is being displayed like so:
<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:
<a href="myurl" onclick='event.preventDefault();myFunction(this.href);'>link</a>
But when I try, I get:
ReferenceError: Can't find variable: myFunction
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.
in my .vue
file, the html is being displayed like so:
<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:
<a href="myurl" onclick='event.preventDefault();myFunction(this.href);'>link</a>
But when I try, I get:
Share Improve this question edited Sep 24, 2017 at 13:28 Stephen asked Sep 24, 2017 at 13:23 StephenStephen 8,2487 gold badges47 silver badges59 bronze badges 1ReferenceError: Can't find variable: myFunction
- You can also do something like this: codepen.io/Kradek/pen/zEopZd?editors=1010 – Bert Commented Sep 24, 2017 at 16:14
1 Answer
Reset to default 7This 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):
<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 ponents and use them instead.