V
V
Vlad Osadchyi2021-12-16 14:02:05
Vue.js
Vlad Osadchyi, 2021-12-16 14:02:05

How to insert buttons in v-html so that when clicked, they call the component's method?

I'm doing something like a messenger on vue2.
It is necessary to make such a feature that the appeal to the user ( @vlad ) in the output message is replaced with a button that opens the modal with the user profile. Basically like Telegram.

With the help of a regular expression, I can find such calls and replace them with a link. But I don't know how to make the button click call the component's method.

Here's an example: https://codesandbox.io/s/vibrant-sky-p399o?file=/s...

As you can see, the button does not call the testClick method .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-12-16
@VladOsadchyi

In order to bind event handlers, attributes, etc., instead of sticking a string in, v-htmlyou need to compile it as a component template, something like this:
<component :is="getComponent(text)"></component>

methods: {
  getComponent(text) {
    return Object.assign(Vue.compile(`<div>${this.getMessageHtml(text)}</div>`), {
      methods: {
        // сюда пробрасываете нужный вам обработчик клика
      },
    });
  },
  ...

Although, in this case, it is not necessary to do this, you can use delegation - instead of buttons, hang the click handler somewhere higher, for example:
<div v-html="getMessageHtml(text)" @click="onClick"></div>

methods: {
  onClick(e) {
    if (e.target.tagName === 'BUTTON') {
      // убедились, что клик был по кнопке - теперь делайте чего там вам надо
    }
  },
  ...

A
Alexander Taratin, 2015-07-15
@mamut

https://github.com/eligrey/FileSaver.js/
Version for ie9
https://qw0101.github.io/csvtabletest/ see source page

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question