【问题标题】:Returning value from ajax in vuejs从 vuejs 中的 ajax 返回值
【发布时间】:2020-05-10 10:28:44
【问题描述】:

我试图将整数 (id) 传递给调用 api 的函数。 api 然后检查传递的 id 是否与数据库中的任何数据匹配,并返回与 id 关联的名称。我在 laravel 旁边使用 vue.js。下面是我的代码。

<tr v-for="store in storeList" :key="store.id">
                    <td>{{ getNodeName(store.store_name) }}</td>
</tr>

 getNodeName(nodeId)
            {
                axios.get('api/store/getNodeName/'+nodeId).then(function (response){
                   return response.data[0].name;
                });
            }

现在的问题是如何让结果打印在 td 标签内。显然从ajax返回不起作用,我尝试将它全部推送到一个数组并再次打印它,但它也不起作用。 谢谢

【问题讨论】:

  • this.storeList.push(response.data[0]);

标签: php ajax laravel vue.js


【解决方案1】:

假设您的 API 工作正常,那么您做错的第一件事就是当 Promise 解决时您从回调返回,而不是从 getNodeName 方法返回。

实现您想要的一个简单方法是在 mounted 生命周期钩子中循环遍历您的 storeList(假设它是一个道具)(在此处使用 arrow functions

...

<tr v-for="node in nodes" :key="node.id">
  <td>{{ node.name }}</td>
</tr>

...

data() {
  return {
    nodes: []
  };
},
mounted() {
  this.storeList.forEach(store => this.getNodeName(store.store_name));
},
methods: {
  getNodeName(nodeId) {
    axios.get('api/store/getNodeName/' + nodeId)
      .then(response => this.nodes.push({ id: nodeId, name: response.data[0].name }))
  }
}

...

如果可能的话,您可能还希望将其转换为一个 API 调用,因为您正在进行 storeList.length 调用。

【讨论】:

    【解决方案2】:

    您可以创建一个 storelist 循环并从那里获取 nodeId,然后进行 API 调用。

    <tr v-for="store in storeData" :key="store.id">
    
    <td>{{store.name}} </td>
    
    
    </tr>
    
    data(){
    
    return{
      storeData : []
    
    
       };
    

    },

    created(){
    for(var i=0; i<this.storeList.length; i++){
      axios.get('api/store/getNodeName/' + this.storeList[i].store_name)
         .then(response => this.storeData.push({ id: this.storeList[i].store_name, 
         name:  response.data[0].name  
      }))
       }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 2016-08-23
      • 2020-01-10
      • 2017-01-18
      相关资源
      最近更新 更多