简体   繁体   English

Vue.js v-for不在应用程序中工作

[英]Vue.js v-for not working in the application

I have a Vue.js application. 我有一个Vue.js应用程序。 I get a list via ajax: 我通过ajax获得一个列表:

    $.ajax({
    method: 'POST',
    dataType: 'json',
    url: this.base_info.url + 'getavailability?token=' + this.token,
    data: this.search_info,
    success: function (list) {
        this.results = list;
        console.log(list);
    }.bind(this)
});

And here is the result: 这是结果:

{
  "success": "true",
  "error": "false",
  "items": [
    {
      "relation_id": "9961",
      "recommendation_id": "1",
      "combination_id": "3",
      "total_fare": "5530000",
      "quantity_adult": "1",
      "totalfare_adult": "5,530,000",
      "quantity_child": "0",
      "totalfare_child": "0",
      "quantity_infant": "0",
      "totalfare_infant": "0",
      "airlines_name": "Qatar Airways",
      "airline_logo": "QR"
    },
    {
      "relation_id": "9962",
      "recommendation_id": "1",
      "combination_id": "4",
      "total_fare": "5530000",
      "quantity_adult": "1",
      "totalfare_adult": "5,530,000",
      "quantity_child": "0",
      "totalfare_child": "0",
      "quantity_infant": "0",
      "totalfare_infant": "0",
      "airlines_name": "Qatar Airways",
      "airline_logo": "QR"
    },
  ]
}

When I loop through the result via Vue js, it outputs and empty row in my table. 当我通过Vue js遍历结果时,它输出并在我的表中清空行。

<div v-for="item in results.items">
     <span class="big db">{{item.total_fare}}</span>
</div>

I don't know which part has problems. 我不知道哪个部分有问题。

In your success handler attach the items like 在您的成功处理程序中附加类似的项目

this.$set('results.items', list);

This might force the digest cycle and in case results.items was not originally declared in your data, they will be evaluated. 这可能会强制使用摘要周期,如果最初未在数据中声明results.items,则会对其进行评估。

The issue you are having is that this within your ajax enclosure does not equate to your Vue js instance. 您遇到的问题是,您的ajax机箱中的这个不等于您的Vue js实例。 To solve the issue you can do the following just before your ajax call, assign this to a variable 要解决此问题,您可以在ajax调用之前执行以下操作,将其分配给变量

    var vm = this;

     $.ajax({
    method: 'POST',
    dataType: 'json',
    url: this.base_info.url + 'getavailability?token=' + this.token,

    data: this.search_info,
    success: function (list) {
        const json = JSON.parse(list) as DataType_Of_Results;
        vm.results = json;
    }
});

Notes: 笔记:

  1. Define a class that encapsulates the properties returned 定义一个封装返回属性的类

     class result{ relation_id: string, recommendation_id: string, combination_id: string, total_fare: string, quantity_adult: string, totalfare_adult: string, quantity_child: string, totalfare_child: string, quantity_infant: string, totalfare_infant: string, airlines_name: string, airline_logo: string } 

In Data section on you Vue Instance 在Vue实例的数据部分中

 data:{
    result: new Array<result>()
    },
    method:{
      getresult: function(){


    var vm = this;

     $.ajax({
    method: 'POST',
    dataType: 'json',
    url: this.base_info.url + 'getavailability?token=' + this.token,

    data: this.search_info,
    success: function (list) {
        const jsonResult = JSON.parse(list) as Array<result>;
        vm.results = jsonResult;
    }
      }
    }

First of all, make sure 'results' is defined in the data section of your Vue instance and you will also have to make sure this 'results' defined is of same data type as that of the data returned by 'list'. 首先,确保在Vue实例的数据部分中定义“结果”,并且还必须确保定义的“结果”与“list”返回的数据的数据类型相同。

Secondly, I think its better to console log 'this.results' rather than 'list' since its 'this.results' you are looping through and not 'list' 其次,我认为更好地控制日志'this.results'而不是'list',因为'this.results'你循环而不是'list'

I think it is because you have an extra , after the last entry 我想这是因为你在最后一次参赛后还有一个额外的

{
  "relation_id": "9962",
  "recommendation_id": "1",
  "combination_id": "4",
  "total_fare": "5530000",
  "quantity_adult": "1",
  "totalfare_adult": "5,530,000",
  "quantity_child": "0",
  "totalfare_child": "0",
  "quantity_infant": "0",
  "totalfare_infant": "0",
  "airlines_name": "Qatar Airways",
  "airline_logo": "QR"
},

] ]

which results in an empty row 这导致空行

"this" in your success callback does not refer to the vue Instance, it refers to jquery. 你成功回调中的"this"并不是指vue实例,它指的是jquery。 you should do 你应该做

var vueInstance = this;
  $.ajax({
  method: 'POST',
  dataType: 'json',
  url: this.base_info.url + 'getavailability?token=' + this.token,
  data: this.search_info,
  success: function (list) {
      vueInstance.results = list;
  }
});

你必须在安装组件时执行ajax请求,为此使用函数created () {ajax ...}mounted () {ajax ...}数据将在div的开始v-for之前

you can use computed 你可以用计算机

 var app = new Vue({ el: '#app', data() { return { results: { "success": "true", "error": "false", "items": [ { "relation_id": "9961", "recommendation_id": "1", "combination_id": "3", "total_fare": "5530000", "quantity_adult": "1", "totalfare_adult": "5,530,000", "quantity_child": "0", "totalfare_child": "0", "quantity_infant": "0", "totalfare_infant": "0", "airlines_name": "Qatar Airways", "airline_logo": "QR" }, { "relation_id": "9962", "recommendation_id": "1", "combination_id": "4", "total_fare": "5530000", "quantity_adult": "1", "totalfare_adult": "5,530,000", "quantity_child": "0", "totalfare_child": "0", "quantity_infant": "0", "totalfare_infant": "0", "airlines_name": "Qatar Airways", "airline_logo": "QR" }, ] } } }, computed: { items() { return this.results.items; } }, }); 
 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> <div id="app"> <div v-for="item in items"> <span class="big db">{{item.total_fare}}</span> </div> </div> 

I think you should simply retrieve your availability array in a Vuex prop, then bind it as computed prop in your component; 我认为你应该只是在Vuex道具中检索你的可用性数组,然后将它作为计算道具绑定在你的组件中; that will make the property reactive and as soon as the api call succeeded you will have the data in the template too. 这将使该属性被激活,并且一旦api调用成功,您也将在模板中获得数据。

so, in actions.js 所以,在actions.js中


async getAvailabilityArray ({commit}) {
  try {
    const data = await apiService.post('getavailability', {token: 'foo', etc})
    commit('mutateAvailabilityArray', data)
  } catch (err) {
    console.error(err)
  }
}

in component.vue 在component.vue中

<template>
  <div>
    <div v-for="item in results.items">
      <span class="big db">{{item.total_fare}}</span>
    </div>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  export default {
    computed: {
      ...mapGetters(['availabilityArray']
    }
  }
</script>

Ooor if not using Vuex, use AsyncComputed prop ( yarn add vue-async-computed ) 如果不使用Vuex,请使用AsyncComputed prop( yarn add vue-async-computed

 <template>
   <div> {{availabilityArray}} </div>
 </template>

 <script>
 export default {
   asyncComputed: {
     async availabilityArray() {
       return await promiseLand()
     }
   },
   methods: {
     promiseLand() {
       return new Promise((resolve, reject) => {
         apiService.post('getavailability', {token: 'foo', etc})
           .then(res => {
             resolve(res)
           }).catch(err => reject(err))
       })
     }
   }
 }
 </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM