3

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

1

1 Answer 1

7

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):

<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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this. BTW, I am open to this being done in a different way, but this particular server returned html relies on a call to another service (with an obscured API key) to get its data and it can not be embedded in the app itself. Do you have another suggestion? This is the only place in my app where this type of thing is (seemingly) necessary.
I suppose I could return the constituent html parts, and THEN apply the click handler to those inside a broken up template, do you think that would be better?
Aye, if you can get the template into your component - and then bind your component methods to the dom parts it's a lot better (still not the best but better). I'd even go ahead and create a custom component that receives html path to download, selectors and handlers to bind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.