Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The problem

When I called the select selector component of Ele. me these days, I found that its select selector could not adapt the width according to the content, as shown in the figure

As you can see, the content of the first option is longer than the length of the select box. However, the width of the select box cannot be automatically widened according to the content of the option, so only part of the content can be seen. The experience is bad.

The select selector is also implemented internally with input.

So the question is how the width of the input ADAPTS to the content.

To solve

There’s a lot of discussion online about this.

So here’s my solution

When selecting the content of the option, take the content of the option, and multiply it by a value (variable, non-fixed, based on the content of the option) to get the width of the content of the option, and then dynamically set the width of the select box.

You can listen for changes in the value of the el-select box in watch.

The code is as follows:

  <el-select v-model="value" placeholder="Please select" :style="{'min-width': selectWidth}">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
Copy the code
var Main = {
    data() {
      return {
        options: [{
          value: 'I'm the answer cp3, I'm the answer cp3, I'm the answer cp3'.label: 'I'm the answer cp3, I'm the answer cp3, I'm the answer cp3'
        }, {
          value: 'option 2'.label: 'Double skin milk'
        }, {
          value: 'option 3'.label: Oyster omelet
        }, {
          value: 'option 4'.label: 'Dragon beard noodles'
        }, {
          value: 'option 5'.label: 'Peking Duck'}].value: ' '.selectWidth: ' '}},watch: {
      value (val) {
        this.selectWidth = val.length * 14 + 'px' // 14 is dynamic and variable}}}var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
Copy the code

Note: the value of 14 in val.length * 14 varies according to the content of your option. If it is pure Chinese, the value needs to be larger. I want you to change it according to your own content.

If you have other plans, welcome to comment and exchange.