首页 > 解决方案 > 如何在 @click 使用 Vue3 调用的异步函数中清空数组

问题描述

我使用带有@click 的按钮对数据库进行异步调用以检索和显示数据。

“行”变量(数组)应处理此数据,然后数据应显示在选项卡中。

每次单击该按钮时,rows 变量都会使用新数据增加其大小。我想用新数据替换数组。

我不明白为什么会保留以前点击的数据。

我想在每次单击按钮之前清空作为数组的“行”变量。

模板 :

  <q-select  rounded outlined bottom-slots v-model="version" :options="options" label="Select Database Version"  :dense="false" :options-dense="false" >  </q-select>

  <div class ="searchButton">
  <div  class="q-pa-md">
      <div class="q-gutter-md" style="max-width: 300px">
        <q-input v-model="gene" label="Find your gene !" />
        <q-btn @click="search(version)" label="Search" />
        <q-icon name="search" />
      </div>
    </div>
 </div>
<br/>
<br/>

  <div v-if="loading === 'found'" class="q-pa-md" id = 'table'>
    <q-table
      title="Ligand - Receptor"
      :rows="rows"
      :columns="columns"
      row-key="name"
    />
  </div>
   <div v-else-if="loading === 'notfound'" class="warning">
  Sorry , no record was retrieved for this input !
  </div>


</template>

脚本 :

<script lang="ts">
import { defineComponent, toRefs,ref,reactive,onMounted,onBeforeUpdate,onUpdated} from 'vue';
import { ReleasesApi  } from '../api/ReleasesApi'; 
import Release from '@/models/Release';
import Interactor from '@/models/Interactor';

import { useEngine } from '../composition/searchEngine';

export default defineComponent ({
setup (props, context) {
  
   const gene  = ref<string>("TIE1")
   const version = ref<string>("1");

   const options   = ref<string[]>(["1","2"]);
   const loading   = ref<string>("empty");
   const error     = ref<boolean>(false);


   let ids_interactor    = <number[]>([]);
   let interactors    = <Interactor[]>([]);

  // let rows = ref([{}]);
    let rows = ref([{
      official_symbol_ligand : "TEST" ,
      synonyms_ligand : "TEST",
      official_name_ligand : "TEST",
      alternative_names_ligand :  "TEST",
      official_symbol_receptor : "TEST" ,
      synonyms_receptor : "TEST" ,
      official_name_receptor : "TEST" ,
      alternative_names_receptor :  "TEST" ,
    }]);

const columns = [
   { name: 'official_symbol_ligand',required: true,label: 'Ligand : Official Symbol',align: 'left',field: row => row.official_symbol_ligand,format: val => `${val}`,sortable: true } ,
   { name: 'synonyms_ligand',required: true,label: 'Ligand :  Synonyms',align: 'left',field: row => row.synonyms_ligand,format: val => `${val}`,sortable: true } ,
   { name: 'official_name_ligand',required: true,label: 'Ligand : Name',align: 'left',field: row => row.official_name_ligand,format: val => `${val}`,sortable: true } ,
   { name: 'alternative_names_ligand',required: true,label: 'Ligand : Alternative Names',align: 'left',field: row => row.alternative_names_ligand,format: val => `${val}`,sortable: true } ,

  { name: 'official_symbol_receptor',required: true,label: 'Receptor : Official Symbol',align: 'left',field: row => row.official_symbol_receptor,format: val => `${val}`,sortable: true } ,
   { name: 'synonyms_receptor',required: true,label: 'Receptor :  Synonyms',align: 'left',field: row => row.synonyms_receptor,format: val => `${val}`,sortable: true } ,
   { name: 'official_name_receptor',required: true,label: 'Receptor : Name',align: 'left',field: row => row.official_name_receptor,format: val => `${val}`,sortable: true } ,
   { name: 'alternative_names_receptor',required: true,label: 'Receptor : Alternative Names',align: 'left',field: row => row.alternative_names_receptor,format: val => `${val}`,sortable: true } 
   ];

 
  onMounted (   () =>  {console.log("Mounted") });

  onBeforeUpdate(() => { console.log("onBeforeUpdate") ; } )


  //valled when reactive data changes and before re-render
  //onUpdated(() => { console.log("onUpdated") ; rows.value = [{}]; } ); 

 async function  search () {

           console.log("async search function called !")
           console.log(gene.value +" "+ version.value );
           rows.value = [];
           /* First database request */

           // const fetchData = async function (){
                  try {
                      ids_interactor =  await ReleasesApi.getIndexInteractions(version.value,gene.value);
                  } catch (e) {
                      if (e instanceof TypeError) {error.value = true }
                      }

                      for (const type of ["ligand","receptor"] ) {
                          for (const id of ids_interactor) {
                            try {
                                const interactor : Interactor =  await ReleasesApi.getInteractorsUsingTypeAndIndex(type,id);
                                interactors.push(interactor[0]);
                                //ajout dans le hash
                            } catch (e) {
                                if (e instanceof TypeError) {error.value = true }
                                }
                          }
                      }
                // outside will not work
                for (let i = 0; i < interactors.filter(interactor=>interactor.type=="ligand").length; i++) {
                 
                  rows.value.push( { 
                        official_symbol_ligand  : interactors.filter(interactor=>interactor.type=="ligand")[i].official_symbol , 
                        official_symbol_receptor  : interactors.filter(interactor=>interactor.type=="receptor")[i].official_symbol , 
                        synonyms_ligand  : interactors.filter(interactor=>interactor.type=="ligand")[i].synonyms , 
                        synonyms_receptor  : interactors.filter(interactor=>interactor.type=="receptor")[i].synonyms , 
                        official_name_ligand  : interactors.filter(interactor=>interactor.type=="ligand")[i].official_name , 
                        official_name_receptor  : interactors.filter(interactor=>interactor.type=="receptor")[i].official_name , 
                        alternative_names_ligand  : interactors.filter(interactor=>interactor.type=="ligand")[i].alternative_names , 
                        alternative_names_receptor  : interactors.filter(interactor=>interactor.type=="receptor")[i].alternative_names
                    });
                  }
             // }

   //fetchData()

   console.log(rows.value.length);

   //console.log(rows.value[0].interactor_id) // That'ok 
   if(rows.value.length == 1) { loading.value  = "notfound"; } else { loading.value  = "found"; }


  }

   return { loading,error,version,ids_interactor,gene,options,columns,rows,search}
}

});

  </script>

标签: async-awaitvuejs3

解决方案


推荐阅读