[Vuejs]-Vue 2 select2 custom template for label

5👍

As Vue-select Github: L324 and Vue-select Github: L539, uses <slot name="selected-option"> will be one solution.

Updated: from Vue-select Github you will see there is one parent slot = selected-option-container, but I found it hasn’t been deployed to the dist. In future, you should be able to use this slot to custom the whole container and the selected options.

Like below demo:

Vue.component('v-select', VueSelect.VueSelect)

new Vue({
  el: '#app',
  data: {
    options: [
      {
          title: 'Read the Docs',
          icon: 'fa-book',
          url: 'https://codeclimate.com/github/sagalbot/vue-select'
        },
        {
          title: 'View on GitHub',
          icon: 'fa-github',
          url: 'https://codeclimate.com/github/sagalbot/vue-select'
        },
        {
          title: 'View on NPM',
          icon: 'fa-database',
          url: 'https://codeclimate.com/github/sagalbot/vue-select'
        },
        {
          title: 'View Codepen Examples',
          icon: 'fa-pencil',
          url: 'https://codeclimate.com/github/sagalbot/vue-select'
        }
    ]
  }
})
body {
  font-family: "Source Sans Pro", "Helvetica Neue", Arial, sans-serif;
}

h1,.muted {
  color: #2c3e5099;
}

h1 {
  font-size: 26px;
  font-weight: 600;
  text-rendering: optimizelegibility;
  -moz-osx-font-smoothing: grayscale;
  -moz-text-size-adjust: none;
}

#app {
  max-width: 30em;
  margin: 1em auto;
}

#app .dropdown li {
  border-bottom: 1px solid rgba(112, 128, 144, 0.1)
}

#app .dropdown li:last-child {
  border-bottom: none;
}

#app .dropdown li a {
  padding: 10px 20px;
  display: flex;
  width: 100%;
  align-items: center;
  font-size: 1.25em;
}

#app .dropdown li a .fa {
  padding-right: 0.5em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<script src="https://unpkg.com/vue-select@latest"></script>
<div id="app">
  <h1>Vue Select - Custom Option Templating</h1>
  <v-select :options="options" label="title">
    <template slot="selected-option" slot-scope="option">
      <div class="flex">
        <div class="col">
          <span class="fa" :class="option.icon"></span>
          <span>Selected item: {{ option.title }}</span>
        </div>
      </div>
    </template>
    <template slot="option" slot-scope="option">
        <span class="fa" :class="option.icon"></span>
        {{ option.title }}
    </template>
  </v-select>
</div>
👤Sphinx

Leave a comment