Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue event handler on dynamically inserted string does not work

This is my code:

<template>
    <div>      
      <div v-html="data"></div> <button v-on:click="replace">Click Me to replace div contents</button>
    </div>
</template>
<script>
export default {
  data() {
    return {
      data: "I will be replaced once you click on button"
    }
  },
  methods: {
    clickMe() {
      alert("worked");
    },
    replace(){
      this.data = "Why does click me not work? It is loaded from server via ajax <a href v-on:click.prevent='clickMe'>Click Me</a>";
    }
  }
};
</script>

Here if I click on Click Me to replace div contents the content is replaced but the event handler clickMe does not fire. This data would come from server and I need to compile this string and use it from within the Vue's context so Vue can handle events etc.

How can I have the dynamic string downloaded from server work? I am using Vue 2.

like image 326
Tim Liberty Avatar asked Nov 09 '17 13:11

Tim Liberty


1 Answers

Since v-html isn't compiled you will have to create a mini component like this to get around the issue:

new Vue({
  el: '#app',
  data () {
    return {
      data: ``
    }
  },
  
  computed: {
    compiledData () {
      return {
      	template: `<p>${this.data}</p>`
      }
    }
  },
  
  methods: {
    replace () {
       this.data = `Now click on me <a href='#' @click.prevent='alert("yo")'> here </a>`
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>


<div id="app">
  <component :is="compiledData" ></component>
  <button v-on:click="replace">Click Me to replace div contents</button>
</div>

The above code compiles the string content and thus you can run/execute the function as intended

like image 75
samayo Avatar answered Oct 27 '22 15:10

samayo