2017-03-17 48 views
1

在这里,在Vue的分量I动态接收消息从服务器:如何添加点击处理函数在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!'); 
    } 
    } 
}; 

消息具有类=“行动”的链接。

作为例子:

response.data.message = 'Some text... <a class="action" href="/test">test</a>'; 

模板:

<div v-html="windowText"></div> 

我如何可以添加一些点击处理函数这个链接?

我想编辑response.data.message与替换功能是这样的:

this.windowText = responseText.replace(
    new RegExp("class='action'", 'g'), 
    'v-on:click.stop="myclick"' 
); 

但它不工作。

请帮帮我。

而当然,我无法编辑response.data.message。

回答

1

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

Example

+0

非常感谢。这真的很有帮助。但是我发现了一些负面影响。如果链接包含其他元素test然后事件适用于像b或img这样的嵌套元素。 –

+0

@AlexSemenov我更新了示例笔来处理这种情况。 – Bert