首页 > 解决方案 > 如何从动态填充的选择框中侦听初始更改事件

问题描述

由于 HTTP 请求,我在 Vue.js 中有一个动态填充的选择框。我正在监听@change事件以运行一些程序代码,但是该事件仅在用户进行更改@change时触发。它不会捕获填充选择框并选择值时发生的初始事件。

这是我的代码:

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>

选择组件上有一个@change处理程序,用于更新.label属性。该.label属性用于输出文本:“当前大小为 {{label}}”。

问题是第一次填充@change选择框时不会触发。如果您手动更改它,它可以正常工作。

我怎样才能捕捉到选择框上的初始变化?

标签: vue.js

解决方案


原因是,的价值selectedSize没有改变,只有选项。我会建议为标签使用计算,这样你就可以省略@change事件

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 
         : ''
    }
}

最好也为每个选项获得标签

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

推荐阅读