How to bind to attribute in Vue JS?

Found in Google this topic when searching $attrib. Question don't specify what value is used (maybe not defined before) For ANY parent attribute or to FILTER it, use something like that:

<template>
  <component
    is="div"
    v-bind="$attrs"
    class="bg-light-gray"
  >
  EXAMPLE
  </component>
</template>

This instruct to create specific, dynamic and context aware, wrapper:

  • v-bind="$attrs" instruct to take all sended params. Not needed to declare as param object in script.
  • Work even with valid html attribute like class
  • example above mix static class with parent and join it. Use ternary operator (x=1?x:y) to choose proper one.
  • bonus: by "is" you can dynamically set tag like header or secion instead of div
  • $attrs can be binded to any tag in component so this easily enable simple transmission for one tag dynamic attributes like you define class for <input /> but wrapper and actions are added in component

Source with description: https://youtu.be/7lpemgMhi0k?t=1307


In your template:

<a :href="href">

And you put href in data:

new Vue({
  // ...
  data: {
    href: 'your link'
  }
})

Or use a computed property:

new Vue({
  // ...
  computed: {
    href () {
      return '/foo' + this.someValue + '/bar'
    }
  }
})

Just complementing ... solve the interpolation error (simple solution, I am Junior front-end developer): Example post object in a loop:

  • instead of
    <a href="{{post.buttonLinkExt}}">
  • try this way
    <a v-bind:href="post.buttonLinkExt">

Use javascript code inside v-bind (or shortcut ":") :

:href="'/Library/@Model.Username' + myVueData.Id"

and

:id="'/Library/@Model.Username' + myVueData.Id"

Update Answer

Some directives can take an “argument”, denoted by a colon after the directive name. For example, the v-bind directive is used to reactively update an HTML attribute:

<a v-bind:href="url"></a>

Here href is the argument, which tells the v-bind directive to bind the element’s href attribute to the value of the expression url. You may have noticed this achieves the same result as an attribute interpolation using href="{{url}}": that is correct, and in fact, attribute interpolations are translated into v-bind bindings internally.

Tags:

Vue.Js