简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM