Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                .block
  #app

script#vue-app(type="text/x-template")
  div
    SelectBox(
      v-model="$data.optionId"
      :options="$data.options"
      placeholder="選択してください"
    )
  
script#select-box(type="text/x-template")
  .select(ref="elRoot")
    .select__inner(@click="onSelectBoxClick") {{ _selectedText || $props.placeholder }}
    .select__over
      template(v-if="$data.isSelecting")
        .overlay
          .overlay__search
            input.search(
              ref="elSearch"
              v-model="$data.searchText"
              @click="onSearchAreaClick"
              @keydown="onSearchKeyDown"
            )
          .overlay__list
            RecycleScroller(
              ref="scroller"
              class="select-list"
              :items="_filteredOptions"
              :itemSize="40"
              keyField="id"
              v-slot="{ item, active }"
            )
              .select-item(
                tabindex="0"
                :class="{ [`js-active-item-${item.id}`]: active }"
                @click="onSelect(item.id)"
                @keydown="onItemKeyDown"
              )
                | {{ item.text }}

              
            
!

CSS

              
                * {
  box-sizing: border-box;
}

.block {
  max-width: 300px;
  margin: 0 auto;
}

$box-height: 60px;

.select {
  $root: &;

  position: relative;

  &__inner {
    position: relative;
    display: flex;
    align-items: center;
    height: $box-height;
    padding: 0 16px;
    background-color: #f5f6f7;
    border-radius: 5px;
    cursor: pointer;
    
    &::after {
      position: absolute;
      top: 50%;
      right: 15px;
      width: 10px;
      height: 10px;
      content: '';
      border-left: solid 2px #ccc;
      border-bottom: solid 2px #ccc;
      transform: translate(-50%, -50%) rotate(-45deg);
    }
  }

  &__over {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 100%;
  }
}

$item-height: 40px;

.overlay {
  overflow: hidden;
  border-radius: 5px;
  box-shadow: 0 7px 15px 0 rgba(63, 75, 95, 0.15), 0 0 10px 0 rgba(109, 123, 135, 0.05);

  &__search {
    height: $box-height;
    border-bottom: solid 1px #ebedf0;
  }
}

.search {
  display: flex;
  align-items: center;
  height: 100%;
  width: 100%;
  padding: 20px 16px;
  background-color: #fff;
  font-size: 16px;
  outline: 0;
  border: 0;
}

.select-list {
  max-height: 5 * $item-height + 2 * 8px;
  padding: 8px 0;
  overflow-y: scroll;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 7px 15px 0 rgba(63, 75, 95, 0.15), 0 0 10px 0 rgba(109, 123, 135, 0.05);
}

.select-item {
  display: flex;
  align-items: center;
  height: $item-height;
  padding: 0 16px;
  corsor: pointer;
    
  &:hover {
    background-color: #f6fafe;
  }
    
  &:focus {
    background-color: #f6fafe;
  }
}

/** VirtualScrollerのカスタマイズ */
.select-list {
  .vue-recycle-scroller__item-wrapper {
    overflow: visible;
  }

  .vue-recycle-scroller__item-view {
    &:focus-within {
      z-index: 1;
    }
  }
}
              
            
!

JS

              
                Vue.use(VueVirtualScroller);

/** キーボードの入力コード */
const KEY_CODES = {
  ENTER: 13,
  UP: 38,
  DOWN: 40,
};

Vue.component('SelectBox', {
  template: '#select-box',
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    value: Number,
    options: Array,
    placeholder: String,
  },
  data() {
    return {
      isSelecting: false,
      focusIndex: 0,
      searchText: '',
      isReturnFocus: false,
    };
  },
  computed: {
    _selectedText() {
      const option = this.$props.options.find((option) => option.id === this.$props.value);
      return option ? option.text : '';
    },
    _filteredOptions() {
      return this.$props.options.filter((option) => option.text.includes(this.$data.searchText));
    }
  },
  mounted() {
    // windowにイベントリスナーをセットする
    window.addEventListener('click', this._onBlurHandler = (event) => {
      // targetがコンポーネントの中に含まれているものなら何もしない
      if (this.$refs.elRoot.contains(event.target)) {
        return;
      }
      this.$data.isSelecting = false; // 表示フラグをOFFにする
    });
  },
  beforeDestroy() {
    // コンポーネントが破棄されるタイミングにイベントリスナーも消す
    window.removeEventListener('click', this._onBlurHandler);
  },
  methods: {
    focusItem(index) {
      if (!this.$refs.scroller) {
        console.warn('scroller not found');
        return;
      }
      this.$data.focusIndex = _.clamp(index, 0, this._filteredOptions.length - 1);
      const option = this._filteredOptions[this.$data.focusIndex];
      const elItem = this.$refs.scroller.$el.querySelector(`.js-active-item-${option.id}`);
      if (!elItem) {
        console.warn('focus item lost!');
        return;
      }
      elItem.focus();
    },
    blurHandler() {
      if (this.$data.isReturnFocus) {
        this.focusItem(this.$data.focusIndex);
      }
    },
    onSelectBoxClick() {
      this.$data.isSelecting = true;
      this.$nextTick(() => {
        this.$refs.elSearch.focus();
      });
    },
    onSearchAreaClick() {
      this.$data.isReturnFocus = false;
      this.$nextTick(() => {
        this.$refs.elSearch.focus();
      });
    },
    onSelect(optionId) {
      this.$emit('change', optionId);
      this.$data.isSelecting = false;
    },
    onSearchKeyDown(event) {
      if (event.keyCode === KEY_CODES.DOWN) {
        event.preventDefault();
        event.stopPropagation();
        // 上にスクロールしてからフォーカスする
        this.$refs.scroller.scrollToItem(0);
        window.setTimeout(() => {
          this.focusItem(0);
          this.$data.isReturnFocus = true;
          const elItems = this.$refs.scroller.$el.querySelectorAll('.select-item');
          elItems.forEach((elItem) => {
            elItem.addEventListener('blur', this.blurHandler);
          });
        }, 10);
        return;
      }
    },
    onItemKeyDown(event) {
      event.preventDefault();
      event.stopPropagation();

      // Enterキー
      if (event.keyCode === KEY_CODES.ENTER) {
        const option = this._filteredOptions[this.$data.focusIndex];
        const elItem = this.$refs.scroller.$el.querySelector(`.js-active-item-${option.id}`);
        elItem.click();
        return;
      }

      // ↑キー
      if (event.keyCode === KEY_CODES.UP) {
        if (this.$data.focusIndex <= 0) {
          this.$data.isReturnFocus = false;
          this.$refs.elSearch.focus();
          return;
        }
        this.focusItem(this.$data.focusIndex - 1);
        return;
      }

      // ↓キー
      if (event.keyCode === KEY_CODES.DOWN) {
        this.focusItem(this.$data.focusIndex + 1);
        return;
      }
    },
    // onUpdateは更新完了していない気がするので上手くいかなかった
    // onUpdate(startIndex, endIndex) {
    //   console.log(startIndex, endIndex);
    //   window.setTimeout(() => {
    //     this.focusItem(this.$data.focusIndex);
    //   }, 0);
    // },
  }
});

new Vue({
  el: '#app',
  template: '#vue-app',
  data() {
    return {
      optionId: -1,
      options: _.times(500).map((index) => ({
        id: index,
        text: `テスト${index}`,
      })), 
    };
  },
});

              
            
!
999px

Console