itsource

Vue JS에서 v-for 루프 중에 로컬 변수 할당

mycopycode 2022. 8. 28. 09:55
반응형

Vue JS에서 v-for 루프 중에 로컬 변수 할당

기본적인 문제로 보이는 것에 대한 해결책을 찾는 데 어려움을 겪고 있어요.

v-for 루프를 사용하여 일부 콘텐츠를 생성하는 템플릿이 있습니다. 이 콘텐츠 내에서 콘텐츠를 확인하는 기능을 실행해야 합니다.ID는 다른 목록의 ID와 일치합니다.일치하는 경우 해당 데이터를 가져와 루프에 표시해야 합니다. 현재 해당 데이터를 얻는 유일한 방법은 여러 번 확인하는 기능을 실행하는 것입니다.

methods: {
findClientName (clientId) {
  for (let name of this.clientList) {
    if (name.id == clientId) {
      return {
        name
      }
    }
  }
}

<v-card-text>
    {{ findClientName(item.client_id).name.f_name }}
    {{ findClientName(item.client_id).name.l_name }}
</v-card-text>

원하는 데이터의 모든 부분에 대해 메서드를 호출해야 하므로 매우 비효율적인 방법인 것 같습니다. 템플릿 내의 로컬 변수에 할당하는 방법은 없습니까?

{ clientData = findClientName(item.client_id) }
{{ clientData.f_name }}
{{ clientData.l_name }}

내가 뭘 놓쳤지, 안 생각하고 있지?

를 사용하는 것이 좋습니다.computed이 경우 속성을 루핑합니다.v-for고객님의 사례를 시뮬레이트하기 위한 예를 제시했습니다.

new Vue({
  el: '#app',
  data: {
    a: ["aaa", "bbb", "ccc", "ddd", "eee", "fff"],
    b: ["bbb", "sss", "ccc", "eee"]
  },
  computed: {
    isInA() {
      return this.b.filter((item) => {
        return this.a.includes(item)
      })
    }
  }

})
<!DOCTYPE html>
<html>

<head>
  <meta name="description" content="Vue.delete">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>
</head>

<body>
  <div id="app">
    <div v-for="item in isInA">
      {{item}}
    </div>
  </div>

어레이에 다음과 같은 오브젝트가 포함되어 있는 경우 다음과 같은 것이 필요합니다.

computed:
 cpt_clients(){
return this.clientList.filter((cl)=>{
                          return this.otherList.findIndex(item=>{return item.id==cl.id;})!==-1;
                        });
         }
       }

템플릿에서 다음을 수행합니다.

  <v-card-text v-for="cl in cpt_clients" >
       {{cl.name}}
        {{cl.id}}
   </v-card-text>

필요한 데이터가 다른 목록에 있는 경우 검색을 수행해야 합니다.사전에 클라이언트 리스트를 정규화하여 템플릿 루프에서 사용할 수 있습니까?다음과 같은 것들이 있습니다.

data () {
  return {
    mapped: [],
    clientList: [...]
  }
},
mounted () {
  this.mapped = this.clientList.map(({ id, f_name, l_name }) => {
    return { [id]: { f_name, l_name } }
  })
}

템플릿은 다음과 같습니다.

<template>
 ...
    <v-card-text v-if="mapped.hasOwnProperty(item.client_id)">
      {{ mapped[item.client_id].f_name }}
      {{ mapped[item.client_id].l_name }}
    </v-card-text>
 ...
</template>

VUE는 어레이 반복을 기본적으로 지원하므로 로컬 변수가 부족한 경우, 즉 값을 단일 요소 어레이로 래핑하는 방법이 가장 좋습니다.

<template v-for="local_variable in [object.longComputationValueProducer().evenMoreCPUWork()]">
    <!-- body guaranteed to be executed exactly 1-->
    <div>{{ local_variable.read }}</div>
    <div>{{ local_variable.read_without_recompute }}</div>
    <div>{{ local_variable.read_again_without_recompute }}</div>
</template>

계산은 localId에 따라 다르기 때문에 메서드보다 낫다고 생각합니다.

computed: {
   getClientsById (clientId) {
     return this.currentClientList.filter((ccl) => { return this.currentClientList.id === localId });
   }
} 


<v-card-text v-for="item in getClientById">
    {{ item.name }}
</v-card-text>


// Second way without methods and computed

<v-card-text v-for="item in currentClientList" v-if=item.id === localId>
    {{ item.name }}
</v-card-text>

언급URL : https://stackoverflow.com/questions/53714999/assign-local-variable-during-a-v-for-loop-in-vue-js

반응형