使用v-for和v-model的数组首选项的预选择选项

时间:2019-05-18 14:53:34

标签: vue.js select

我正在尝试使用v-for预选第一个元素选项。我可以将数据-> SelectedMonth设置为“ 12måneder”-但是数据将是动态的。

我尝试使用:selected(index === 0),但是不适用于v模型。

        <select class="period-control" v-model="selectedMonth">
          <option
            v-for="(period, price) in car.months"
            v-bind:key="price"
            v-bind:value="period.month"
          >{{ period.month }}</option>
        </select>
data() {
  return {
    selectedMonth: ""
  };
},
asyncData(context) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        car: [
          {
            id: "1",
            brand: "VW",
            model: "Transporter",
            variant: "Sport",
            thumbnail:
              "http://pluspng.com/img-png/cargo-van-png-van-png-transparent-image-1878.png",
            mprice: "2700",
            dpayment: "5400",
            months: [
              { month: "12 måneder", smprice: "1500" },
              { month: "24 måneder", smprice: "2500" },
              { month: "36 måneder", smprice: "3500" }
            ]
          },
          {
            id: "2",
            brand: "Nissan",
            model: "Tekna",
            variant: "Sport",
            thumbnail:
              "http://pluspng.com/img-png/cargo-van-png-van-png-transparent-image-1878.png",
            mprice: "3000",
            dpayment: "5400",
            months: [
              { month: "12 måneder", smprice: "1500" },
              { month: "24 måneder", smprice: "2500" },
              { month: "36 måneder", smprice: "3500" }
            ]
          }
        ].find(el => el.id === context.params.id)
      });
    }, 1500);
  });
}

在两种情况下,预期结果均为“ 12Måneder”。

1 个答案:

答案 0 :(得分:0)

如何直接在asyncData中设置selectedMonth的值?

  asyncData(context) {
    return new Promise((resolve, reject) => {
      const car = ...
      const selectedMonth = car.months[0].month;
      setTimeout(() => {
        resolve({
          car,
          selectedMonth
        });
      }, 1500);
    });
  }