默认情况下使用 v-model 选择第一个选项

时间:2021-03-31 07:03:44

标签: vue.js

有人可以帮忙解决这个问题吗?我有一个动态选择下拉列表。默认情况下,“选择您的位置”的第一个默认选项不可见。这是因为 v 模型。我怎样才能让它工作? 我的父组件:

<template>
<div>

<Segments @select-segment-location-event="updateSegmentLocation" :segmentLocation="segmentLocation" />

</div>
</template>

我的子组件:

<template>
      <div class="container">
         <select v-model="segmentLocation" @change="selectSegmentLocation">
            <option selected disabled>Choose your location...</option>
            <option v-for="(segLoc, index) in segmentLocations" 
             :key="index"
            :value="segLoc">{{ segLoc.name }}</option>
         </select> 
      </div>
</template>
<script>
export default {
 data() {
    return {
      segmentLocations: [
            { value: "Residential", name: 'Residential building' },
            { value: "Workplace", name: 'Workplace' },
            { value: "Hospitality", name: 'Hospitality or Retail' },
            { value: "Real Estate", name: 'Real Estate' },
            { value: "Commercial Parking", name: 'Commercial Parking' },
            { value: "Fleets", name: 'Fleets' },
            { value: "Cities & Governments", name: 'Cities & Governments' },
            { value: "Corridor", name: 'Highway, Corridor or Petrol Station' }
    ],
    }
  }
   methods: {
    selectSegmentLocation() {
        this.$emit('select-segment-location-event', this.segmentLocation);
    }
  }
};
</script>

1 个答案:

答案 0 :(得分:0)

据我所知,segmentLocation 变量作为道具传递给 Segments 组件。

你应该避免在子组件中使用 v-model 改变 prop,因为每个组件应该只改变它自己的状态。

我建议进行一些更改,在您的 selectedSegmentLocation 方法中添加一个新的 data 变量,默认值为 "NOT_SELECTED" :

data() {
  return {
    selectedSegmentLocation: "NOT_SELECTED",
    segmentLocations: []
  }
}

然后,在您的模板中,更新 Choose your location... 选项以具有 value 属性:

<option selected value="NOT_SELECTED" disabled>Choose your location...</option>

现在,更新 v-model 和 selectSegmentLocation 方法以使用新变量:

<select v-model="selectedSegmentLocation" @change="selectSegmentLocation">
selectSegmentLocation() {
  this.$emit('select-segment-location-event', this.selectedSegmentLocation);
}

如果您仍想使用传递的属性 segmentLocation 作为默认值,请在 created() 钩子中使用它,但如果您想使用 'NOT_SELECTED' 作为默认值显示 'Choose your location' 选项。

created() {
  this.selectedSegmentLocation = this.segmentLocation ? this.segmentLocation : "NOT_SELECTED";
}

而且,如果您希望能够从父级更改所选值,您可以watch segmentLocation 属性:

watch: {
  segmentLocation() {
    if (this.segmentLocation) {
      this.selectedSegmentLocation = this.segmentLocation;
    }
  }
}