Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I return a Vue JS component in a callback method?

Assume I have a method in a Vue.js component that returns a string to be rendered onto the page:

display: (arg) => {
    return arg.name
}

And in the relevant HTML:

<div html="component.display(arg)">
</div>

This has worked fine for me until now, but now I want to return HTML with some Vue-bound data on it:

display: (arg) => {
    return '<button @click="myMethod(arg)">Click</button>'
}

Obviously, the above doesn't work. My research has led me to believe that the correct approach here would be to create a component and return it, but I just can't seem to get it working. How would I approach this problem?

like image 457
CGriffin Avatar asked Feb 06 '26 23:02

CGriffin


1 Answers

I think what you're after is a dynamic component.

I would use a computed property to return the component definition to take advantage of Vue's reactivity (methods run all the time, computed properties only when required)

<component :is="display" :arg="arg" @click="myMethod"></component>

and...

computed: {
  display () {
    // you weren't clear on the conditions
    // that should cause this to return something different
    // but here is where you would put them
    return {
      props: ['arg'],
      template: `<button @click="$emit('click', arg)">Click</button>`
    }
  }
}

I'm assuming here that myMethod is defined in the parent, hence adding the @click handler on <component> and $emit in the child.


I suppose you could use a method to return the component definition but that feels like it would be quite inefficient and there's probably a better way to do it.

like image 148
Phil Avatar answered Feb 09 '26 12:02

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!