far

vue3 Props로 index하나씩 넘기기 본문

Vue

vue3 Props로 index하나씩 넘기기

Eater 2022. 10. 9. 02:13
<부모 컴포넌트>

<div v-for="(cmt, index) in state.commentList" :key="cmt + index">
      <WrittenCommentsContent
        :dino="state.dino"
        :idCount="state.idCount[index]"
        :comment="cmt"
      />
</div>


const state = reactive({
      dino: props.dino,
      commentList: [],
      replyidNum: [],
      idCount: [],
      counting: 1,
 });


const reply = async () => {
        await axios
          .post(url, body, { headers })
          .then((res) => {
            for (let index = 0; index < res.data.replyList.length; index++) {
              const element = res.data.replyList[index].id;
              if (!state.replyNum.includes(element)) {
                state.replyNum.push(element);
              }
              if (state.replyNum.indexOf(element) !== -1) {
                state.idCount.push(state.replyNum.indexOf(element) + 1);
              } else if (state.replyNum.indexOf(element) == -1) {
                state.idCount.push(state.counting);
                state.counting + 1;
              }
            }
            state.commentList.push(...res.data.replyList);
          });
      } catch (err) {
        console.error(err);
      }
    };

    reply();

DB의 댓글을 뽑아서 댓글을 익명1 익명2 이런식으로 만들고 싶었다.

 

먼저 코멘트를 쓴 유저의 id를 indexOf로 추적해 replyNum 안에 담는다

replyNum안에 동일 아이디가 있다면 indexOf+1로 카운팅

(같은 코멘트를 쓴 유저에게 동일한 넘버링을 해주기 위한 idCount에 저장)

replyNum에 동일 아이디가 없으면 새 유저이므로 익명 뒤의 숫자가 올라간다. 그리고 counting+1

db에서 불러온 댓글을 commentList에 저장하고 자식 컴포넌트로 v-for

 

하지만 idCount를 이 상태 그대로 내려보내면 idCount가 보유한 모든 값이 익명 뒤에 붙기 때문에 state.idCount[index]로 하나씩 분리해서 쏴준다.

 

 

<자식 컴포넌트>

<template>
    <span :class="{ userid: me.id == comment.id }">
        익명{{ idCount }}</span>
</template>
    
<script>
export default {
    props: {
        idCount: {
          type: Number,
          required: true,
        },
    }
    
    setup() {
    
    }
}​
</script>

<style>
.userid {
  color: #AE6FFF;
  font-weight: 500;
 }
</style>

부모 컴포넌트에서 받아온 idCount를 익명 뒤에 붙이기만 하면 끝

'Vue' 카테고리의 다른 글

[Vue.js] Vue의 라이프사이클  (0) 2022.10.09
Comments