繁体   English   中英

如何添加点击处理程序功能以在Vue中动态链接?

[英]How i can add click handler function to dynamically link in Vue?

在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!');
    }
  }
};

消息与class =“action”有链接。

例如:

  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。

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

例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM