【问题标题】:Populating options for select using v-for VueJS after handling load data event在处理加载数据事件后使用 v-for VueJS 填充选择选项
【发布时间】:2019-04-19 00:17:47
【问题描述】:

我有这个使用 Typescript 编写的 VueJS 应用程序。我正在使用 Axios 从我的数据库中获取数据。这很好用,我得到的结果是一个我所期望的数组。当我对这个数组执行console.log 时,我可以看到它是正确的结果。

但是,当我尝试遍历此数组以创建我的选择下拉列表的选项时,我得到一个空白列表。即使我循环的变量是数组,为什么没有出现结果?

编辑:我在此处添加了一张显示 Axios 结果的图片 (response.data)

export default class EditRoute extends Vue {
  result: any;
  selectedRoute: string;
  constructor(){
     super();
     this.selectedRoute = "";
     this.result = [];
 }

  loadData() {
     axios.get('http://localhost:8080/routes')
     .then(response => (this.result = response.data));
  }
}
<select name="routeSelect" v-model="selectedRoute">
   <option v-for="routes in result" v-bind:key="routes.name" v-bind:value="routes.name"> {{ routes.name }} </option>
</select>
<button @click="loadData">Load data</button>

【问题讨论】:

    标签: javascript node.js vue.js vuejs2 vue-component


    【解决方案1】:

    由于您的result 是一个包含一个项目的对象,因此该项目是一个名为routes 的数组,在这种情况下,您应该像这样循环遍历result.routes

     <option v-for="routes in result.routes" v-bind:key="routes.name" v-bind:value="routes.name"> {{ routes.name }} </option>
    

    额外示例

    new Vue({
      el: '#app',
      data: function() {
        return {
          selectedUser: '',
          users: [],
    
        }
      },
      mounted: function() {
        // this.loadData();
        //  this.timer = setInterval(this.loadData, 4000);
      },
    
      methods: {
        loadData: function() {
          axios.get('https://jsonplaceholder.typicode.com/users').then(response => {
            this.users = response.data;
    
          }).catch(e => {
    
          })
        }
      }
    
    })
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
    
    <head>
      <meta charset="utf-8">
      <title></title>
      <script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
      <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
      <script src="https://unpkg.com/vue-axios@2.1.4/dist/vue-axios.min.js"></script>
    </head>
    
    <body>
      <div id="app">
        <select name="userSelect" v-model="selectedUser">
          <option v-for="user in users" v-bind:key="user.id" v-bind:value="user.name"> {{ user.name }} </option>
        </select>
        <button @click="loadData">Load data</button>
      </div>
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      相关资源
      最近更新 更多