这是我的代码:
<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>
上面的代码编译了字符串内容,因此您可以按预期运行/执行函数
关于javascript - 动态插入字符串上的 Vue 事件处理程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47202998/