这是我的代码:

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

这里,如果我点击Click Me to replace div contents,内容将被替换,但事件处理程序clickMe不会触发.这些数据将来自服务器,我需要编译这个字符串,并从Vue的上下文中使用它,以便Vue可以处理事件等.

如何从服务器上下载动态字符串?我正在使用Vue 2.

推荐答案

由于未编译v-html,因此必须创建一个类似这样的小组件来解决这个问题:

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>

上面的代码编译字符串内容,因此您可以按预期运行/执行该函数

Vue.js相关问答推荐

VueJS不会呈现一个名为None的组件""

从组件中检索 Shopware CMS 编辑器中的自定义实体数据

如何以惯用的方式触发 vue3 中同级组件的效果?

是否可以使用 Vuetify/VueJS 为轮播设置默认图像而不是第一个图像?

VueJS中的绑定函数含义

是否可以让 html-webpack-plugin 从 css 生成