3

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

2
  • Have you got a JSFiddle setup you can share? We can edit this to help you. Commented Sep 26, 2018 at 13:05
  • @David.J just update code Commented Sep 26, 2018 at 13:22

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>

3 Comments

On your toggle component definition.
ok, I see. Yes, it also works, probably It's a more elegant solution to use on HTML attributes rather than props
Yeah I use it when I have an element wrapping the actual element I want my attributes to be applied to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.