Vue JS选择默认值不显示

时间:2020-06-02 14:21:26

标签: javascript html vue.js

我正在学习Vue js,并且正在使用v-for列出数据库中的一些数据。有一个嵌套的v-for,其中在select中列出了游览标题。因此,当我选择标题时,其描述如下。

我正在尝试使用option上方的option和嵌套的v-for来设置默认值。我尝试基于v-model =“ selected [item.id]”,但无法使其正常工作。越来越空白了。在用户使用相同的select打开v-model框之前是否可以设置“选择游览”?

enter image description here

enter image description here

<div v-for="(item, index) in hosters" v-bind:key="item.id" class="col-md-6 mb-50">
    <h4 class="mb-0">{{ item.name }} {{ item.lastname }}</h4>

    <div class="tour-options-select">
        <select :id="'select-suggestions' + item.id" name="tour-options-dropdown"
                v-model="selected[item.id]" class="tour-options-dropdown"
                @change="showTour = selected">

            <option selected disabled>{{ selected.value }}</option>
            <option v-for="(tour, key) in item.tours" :key="key"
                    :value="tour.tourID">
                        {{ tour.title }}
            </option>
        </select>
    </div>

    // here each post is listed by selecting its title
    <div v-if="toursObj[selected[item.id]]" class="tour-suggestions">
        <div class="tour-list">
          <div class="tour-list-title">
             <p>{{ toursObj[selected[item.id]].title }}</p>
          </div>
          <div class="tour-list-description">   
                <p>{{ toursObj[selected[item.id]].description }}</p>
          </div>
       </div>
       <div @click="showTour = false" class="close-suggestions">
          <span>X</span>
       </div>
    </div>    
</div>

vue

let app = new Vue({
   el: '#app',
   data: {
      hosters: {},
      selected: {
        value: 'Select a tour'
      },
      toursObj: {},
      advise: {
        isTrue: null,
        message: 'No hoster found'
      },
   },
  methods: {
   searchHoster: function () {
    axios.post('http://localhost/search/searchHoster.php', { "city": this.city }).then((response) => {

        if (response.data != "No hoster found") {
            this.advise.isTrue = false;
            this.hosters = response.data.hosters;
            console.log(this.hosters);

            const TOURS_OBJ = {};
            this.hosters.forEach(hoster => {
                hoster.tours.forEach(tour => {
                    TOURS_OBJ[tour.tourID] = tour;
                });
            });
            this.toursObj = TOURS_OBJ;
        } else {
            this.advise.isTrue = true;
            console.log(response.data);
        }

    }).catch((error) => {
        console.log(error);
    });
},

https://jsfiddle.net/phxjdbku/

1 个答案:

答案 0 :(得分:0)

您在JSfiddle上的示例存在以下问题:

  1. SELECT的v-model引用item.id-但您的项目没有这样的属性
  2. 用于SELECT的v-model指定您的selected对象具有与每个主机的ID对应的键-但您的数据部分将selected定义为字符串而不是对象
  3. 您的默认选项没有value属性
  4. 您的默认选项不是说Select a tour,而是插值selected.value-我们已经知道selected可能没有这样的键

请查看updated fiddle