Stephen
Stephen

Reputation: 8218

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.

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

Upvotes: 3

Views: 5277

Answers (1)

PiniH
PiniH

Reputation: 1941

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.

Upvotes: 7

Related Questions