VueJs-如何在呈现html之前完成异步请求?

问题描述

我使用el-popover尝试显示一些内容,这是代码

<template v-slot:userItem="testData" >
    <template v-if="testData.roleData!=null">
      <el-popover
      v-for ="(item,index) in testData.roleData.split(',')"
      :key="index"
      placement="top-start"
      title="Authority"
      width="200"
      trigger="hover"
      :content="getClaimValue(item.split(':')[0])">
       <el-link  slot="reference" type="primary"  @click="test1(item.split(':')[0])" >{{item.split(':')[1]}}</el-link>
       </el-popover>
    </template>

现在的问题是我看不到content中的el-popover。 我猜这是因为方法getClaimValue()是异步的,下面是代码

private getClaimValue(roleId:any){
    axios.get(`${env.identityServer}/User/GetClaimByRoleId?roleId=${roleId}`)
                .then((response) => {
                    console.log(response.data);
                    return this.updateTransfer(response.data);
                    
                })
                .catch(
                  (error) => {   
                         Message({
                            message: error.message,type: 'error',duration: 3 * 1000
                          })                  
                  });
  }

那是什么问题,我怎么能看到el-popover内容? 非常感谢。

解决方法

您可以尝试将响应数据保存到另一个对象(例如contents)中,而不是尝试通过返回直接从axios请求中获取响应(我认为您无法这样做),当请求完成时, el-popover内容将自动更新。

在您的xxx.vue中:

 export default class Test extends Vue {

       contents: Object = {};// <--- where to store all contents for el-popovers

       private getClaimValue(roleId:any){
           if(!this.contents[roleId]){
             this.contents[roleId] = "loading";
             axios.get(`${env.identityServer}/User/GetClaimByRoleId?roleId=${roleId}`)
                .then((response) => {
                    console.log(response.data);
                    this.contents[roleId] = this.updateTransfer(response.data);
                    
                })
                .catch(
                  (error) => {   
                         Message({
                            message: error.message,type: 'error',duration: 3 * 1000
                          })                  
                  });
             }
           }
          
           return this.contents[roleId];
        }

      
 }