Shorthand Vue bind

Viewed 1109

In vue there are a couple ways to bind a property to an html tag. For example

<span v-bind:style="style"></span>

Where style exists in the current controller, either as a property or as the component data.

A shorter way to do this is to use the v-bind shorthand:

<span :style="style"></span>

I was wondering if there was a shorter way of doing this, or if there is something similar coming in vue 3, something like this I would like:

<span :style></span>

Is this possible?

2 Answers

Edit July 2022:

I tried an even shorter version in the official playground and it works. Just use :="{attr}" and it works. I have not seen this syntax referenced in the docs so I don't know how official this is. You can even omit the double quotes as it is valid html, but the style guide frowns upon that.

<span :={style}></span>

See it in action in the sfc playground.

Note: playground version ATTOW @8dcb6c7


Original Answer:

My best solution so far is to use v-bind

<span v-bind="{style}"></span>

It allows you to pass multiple properties at once and then you actually save space, see for example how an img looks like

<img v-bind="{alt, src, title}" />

For that to work you'd need to write your own directive:

Vue.directive('style', {
  bind: function(el) {
    el.classList.add('style')
  }
})

new Vue({
  el: "#app"
})
.style {
  font-weight: 700;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-style>This is styled.</div>
  <div>This is not styled.</div>
  <div v-style>This is styled again.</div>
</div>

More on Vue directives: https://v2.vuejs.org/v2/guide/custom-directive.html

Related