动态插入的字符串上的 Vue 事件处理程序不起作用 [英] Vue event handler on dynamically inserted string does not work
问题描述
这是我的代码:
<div><div v-html="数据"></div><button v-on:click="replace">点击我替换div内容</button>
模板><脚本>导出默认{数据() {返回 {数据:一旦你点击按钮,我就会被替换"}},方法: {点击我(){警报(工作");},代替(){this.data = "为什么点击我不起作用?它是通过ajax从服务器加载的<a href v-on:click.prevent='clickMe'>点击我</a>";}}};
在这里,如果我点击 Click Me to replace div contents
内容被替换,但事件处理程序 clickMe 不会触发.此数据将来自服务器,我需要编译此字符串并在 Vue 的上下文中使用它,以便 Vue 可以处理事件等.
如何让从服务器下载的动态字符串工作?我正在使用 Vue 2.
由于未编译 v-html,您将不得不创建一个像这样的迷你组件来解决这个问题:
new Vue({el: '#app',数据 () {返回 {数据:``}},计算:{编译数据(){返回 {模板:`<p>${this.data}</p>`}}},方法: {代替 () {this.data = `现在点击我 这里</a>`}}})
<script src="https://unpkg.com/vue@2.5.3/dist/vue.min.js"></脚本><div id="应用程序"><component :is="compiledData" ></component><button v-on:click="replace">点击我替换div内容</button>
以上代码编译字符串内容,因此您可以按预期运行/执行函数
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.
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屋!