Home > Enterprise >  Conditional v-bind in Vue.js
Conditional v-bind in Vue.js

Time:07-11

Is there a way to put a v-bind:something conditionally?

I have this:

<div >
   <div  :handle=".handle" />
</div>

I want the :handle bind to be conditionally activated.

Having it duplicated with a v-if like this:

<div >
   <div v-if="condition"  :handle=".handle"/>
   <div v-else  />
</div>

costs too much performance, as it has to rerender a bunch of stuff inside the .some-stuff div

CodePudding user response:

Give this a try:

<div >
   <div   v-bind="{ [condition && 'handle']: '.handle' }" />
</div>

Got idea from: Passing props dynamically to dynamic component in VueJS

And from docs:

<!-- binding an object of attributes -->
<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>

https://vuejs.org/api/built-in-directives.html#v-bind

  • Related