在 Vue 组件中,我从服务器动态接收消息:
module.exports = {
data() {
return: { windowText: '' }
},
methods: {
showCancelEntrieWindow(){
this.$http.post('/page', {'number' : '123'})
.then(response => {
responseText = response.data.message;
this.windowText = responseText.replace(
new RegExp("class='action'", 'g'),
'v-on:click="myclick"'
);
});
},
myclick(){
console.log('clicked!');
}
}
};
Run Code Online (Sandbox Code Playgroud)
消息有一个带有 class="action" 的链接。
例如:
response.data.message = 'Some text... <a class="action" href="/test">test</a>';
Run Code Online (Sandbox Code Playgroud)
在模板中:
<div v-html="windowText"></div>
Run Code Online (Sandbox Code Playgroud)
如何向此链接添加一些点击处理函数?
我正在尝试使用替换功能编辑response.data.message,如下所示:
this.windowText = responseText.replace(
new RegExp("class='action'", 'g'),
'v-on:click.stop="myclick"'
);
Run Code Online (Sandbox Code Playgroud)
但这不起作用。
请帮我。
当然,我无法编辑response.data.message。
v-html不会编译模板,因此用 Vue 指令替换类不会执行任何操作。
但是,您可以使用本机事件侦听器。
new Vue({
el: "#app",
data:{
windowText: null,
someValueSetOnClick: null
},
methods:{
onHtmlClick(event){
// Check to make sure this is from our v-html because
// we don't want to handle clicks from other things in
// the Vue
if (!event.target.classList.contains("action"))
return;
event.stopPropagation();
event.preventDefault();
this.someValueSetOnClick = "Clicked";
}
},
mounted(){
this.windowText = 'Some text... <a class="action" href="/test">test</a>'
// Add a native event listener to the Vue element.
this.$el.addEventListener("click", this.onHtmlClick)
}
})
Run Code Online (Sandbox Code Playgroud)
例子。