Search code examples
vue.jsvuejs2vue-componentvuexvue-router

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


Solution

  • 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