4

Here in Vue component I receive dynamically message from server:

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

Message have a link with class="action".

As example:

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

In template:

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

How I can add some click handler function to this link?

I am trying to edit response.data.message with replace function like this:

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

But it does not work.

Please help me.

And ofcourse, I can't edit response.data.message.

1 Answer 1

5

v-html will not compile the template, so replacing the class with the Vue directive will not do anything.

You can, however, use a native event listener.

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. It's really helpful. But i detected some negative effect. If link contains other element <a class="test"><b>test</b></a> or <a class="test"><img /></a> Then event applies to a nested element like b or img.
@AlexSemenov I updated the example pen to handle that case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.