Search code examples
vue.jscomponentsslots

How can I make the placeholder of a button dynamic in Vue?


At this moment, I have a component which is a component for a Selectbox which is used throughout the application. I want to set the placeholder dynamically, so that you can use the button wherever you want, and I know you can do this with Vue Slots, but I don't know how:

For example, I want to achieve this:

<SDSelectBox>Amount of Items</SDSelectBox> and another use case <SDSelectBox>How many items do you want?</SDSelectBox>

which basically replaces the placeholder of the item.

Thanks in advance.


Solution

  • You can make the placeholder dynamic by passing a prop to your component and then setting the placeholder to the value of the prop.
    Like so:

    <SDSelectBox :placeHolder="someValueFromCurrentComponent"></SDSelectBox>
    //Inside the SDSelectBox
    <template>
      <select>
       <option value="" disabled selected>{{placeholder}}</option>
    ...
    props: ['placeHolder'],
    

    Or with a slot you can simply insert into the SDSelectBox:

    <select>
     <slot></slot>
    ...
    //parent component
    <SDSelectBox>
     <option value="" disabled selected>{{placeholder}}</option>
    </SDSelectBox>