Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

vue.js - How to listen for the initial change event from a select box that is dynamically populated

I have a select box in Vue.js that is populated dynamically, as a result of an HTTP request. I am listening for the @change event to run some procedural code, however that @change event only triggers when user makes a change. It doesn't catch the initial event that happens when the select box is populated, and a value is selected.

Here's my code:

const app = Vue.createApp({
  methods: {
    handleSelectSize(size) {
      console.log('handleSelectSize', size.target.value);
      const sizeLabels = {
        'S': 'small',
        'M': 'medium',
        'L': 'large'
      };
      this.label = sizeLabels[size.target.value];
    }
  },
  data() {
    return {
        selectedSize: 'M',
      label: '',
        sizeOptions: null
    }
  },
  mounted() {
    window.setTimeout(() => {
        // Dynamically create values for dropdown
        this.sizeOptions = ['S', 'M', 'L'];
    }, 500);
      
  }
});

app.mount('#myApp');
<script src="https://unpkg.com/vue@next" ></script>

<div id="myApp">
  <label>Select Size
    <select v-model="selectedSize" @change="handleSelectSize($event)">
      <option v-for="size in sizeOptions" v-bind:value="size">
        {{ size }}
      </option>
    </select>
  </label>
  <div>
    The current size is {{label}}
  </div>
</div>
question from:https://stackoverflow.com/questions/65836725/how-to-listen-for-the-initial-change-event-from-a-select-box-that-is-dynamically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

the reason is, the value of the selectedSize is not changing, only the options. i will suggest to use computed for the label so you can omit @change event

data(){
   return {
       selectedSize: 'M',
       sizeLabels = {
         'S': 'small',
         'M': 'medium',
         'L': 'large'
       },
       selectedOptions: [] // better initialized this with array           
   }
},
computed:{
   label(){
       return this.selectedOptions.length ? 
         this.selectedOptions[this.selectedSize] // please handle also if key can not be found 
         : ''
    }
}

better yet to get label also for each options

window.setTimeout(() => {
    // Dynamically create values for dropdown
    this.sizeOptions = [{label: 'foo', 'value': 'bar'}, etc];
}, 500);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...