Kaiser91
Kaiser91

Reputation: 343

Vue js passing HTML button name attribute as a PROPS

I created a custom component which contains an HTML button tag, so I'm using this component many times as a shared component into a parent component. I would like to know if I can pass the name attribute from the HTML button tag as a prop, so I can have a dynamically HTML button tag name attribute.

  <div class="toggle">
    <button
      class="btn"
      name="ships">
  </div>

<script>
export default {
  props: {
    ships: {
      type: String,
      required: true,
      default: ''
    }
  }
</script>


 <toggle
    :ships="white"
/>


 <toggle
    :ships="grey"
/>

 <toggle
    :ships="black"
/>

CODE

Upvotes: 3

Views: 3094

Answers (2)

Steven B.
Steven B.

Reputation: 9362

You can do this without using a prop by using inheritAttrs.

export default {
    inheritAttrs: false,
    name: "toggle",
};

And then use $attrs to access any fallthrough attributes e.g. name.

<div class="toggle">
    <button class="btn"
    v-bind:name="$attrs.name">BUTTON </button>
</div>

And then using your component would just be

<div id="app">
    <toggle name="black" />
    <toggle name="grey" />
    <toggle name="white"/>
</div>

Upvotes: 1

Jns
Jns

Reputation: 3257

I've updated your fiddle: https://codesandbox.io/s/00yxy5lqzn

Things I've changed:

Toogle.vue

<button class="btn" v-bind:name="ships">BUTTON </button>

To change an HTML attribute just add an v-bind: in front of it, because you can not use mustaches there.

App.vue

<div id="app">
  <toggle ships="black" />
  <toggle ships="grey" />
  <toggle ships="white"/>
</div>

Removed the double dot -> now the content of the property will be interpreted as an String.

Edit: Alternative you could do it this way (result is the same): <toggle :ships="'black'" /> <-- it's probably the better way

Upvotes: 2

Related Questions