[Vuejs]-How to show element of VueJS component only if this component has v-on attached?

1đź‘Ť

âś…

Components have $listeners property which is the dictionary of functions that are bound to the component on v-on, and I think you could use it for this.

From https://v2.vuejs.org/v2/guide/components-custom-events.html :

{
  focus: function (event) { /* ... */ }
  input: function (value) { /* ... */ },
}

But I’d advise you to follow @kat advise and not to do that. This feels like it was not designed for this, and just think of this more: do you want to have a component that changes its behavior depending on whether it is viewed by something else? Unless you design quantum particle, this is not how components should work in my mind.


I just realized that I have seen the behavior like you want before (although I still think that it’s not worth doing for the buttons, like you comment suggest) – but maybe this will work for you better. Have a look at: https://bootstrap-vue.js.org/docs/components/table This is a table, that has a provider prop that can be a function. It changes the behavior whether you set provider or not – if you do not, it does not invoke the function, but go for item property to get the data out.

This is done, by using v-bind instead of v-on, but the binding is done to the function. This might be better approach as you don’t have to use $listeners anymore and it gives an insight that the behavior is changed depending on whether you set the property to a function or to null

👤Archeg

2đź‘Ť

I would define and send the vOnStatus = true for attached v-on:event
and then do v-if=”vOnStatus” for the elements I want to display

👤kat

Leave a comment