动态插入字符串上的Vue事件处理程序不起作用 [英] Vue event handler on dynamically inserted string does not work

查看:83
本文介绍了动态插入字符串上的Vue事件处理程序不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

如果我点击点击我替换div内容内容被替换但事件处理程序clickMe不会触发。这些数据来自服务器,我需要编译这个字符串并在Vue的上下文中使用它,这样Vue就可以处理事件等。

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.

我怎样才能拥有动态字符串从服务器下载工作?我正在使用Vue 2.

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

推荐答案

由于未编译v-html,您必须创建一个这样的迷你组件解决问题:

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/vue@2.5.3/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

这篇关于动态插入字符串上的Vue事件处理程序不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆