【问题标题】:Select first option by default using v-model默认使用 v-model 选择第一个选项
【发布时间】:2021-06-27 04:33:47
【问题描述】:

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

<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>

【问题讨论】:

  • 您好,您可以在数据选项中添加segementLocation,并使用默认值。喜欢segmentLocation: 'Choose your Location...'

标签: vue.js


【解决方案1】:

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

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

我提出一些更改,在您的data 方法中添加一个新的selectedSegmentLocation 变量,默认值为"NOT_SELECTED"

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

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

<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() 挂钩中使用它,但如果您想显示'Choose your location' 选项,则应该将'NOT_SELECTED' 作为默认值.

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

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

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

【讨论】:

  • 完美运行!谢谢。
猜你喜欢
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 1970-01-01
  • 2019-03-21
  • 2012-02-27
  • 1970-01-01
相关资源
最近更新 更多