最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue.js call method from dynamic html - Stack Overflow

programmeradmin3浏览0评论

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:

ReferenceError: Can't find variable: myFunction

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 1
  • You can also do something like this: codepen.io/Kradek/pen/zEopZd?editors=1010 – Bert Commented Sep 24, 2017 at 16:14
Add a ment  | 

1 Answer 1

Reset to default 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 ponents and use them instead.

发布评论

评论列表(0)

  1. 暂无评论