front-end/Vue.js

구조 분해 문법(destructuring) / ES6

정구 2022. 2. 23. 10:14
728x90

뷰에서 data, methods 등에 접근할 때 this를 사용한다.

 

이를 구조 분해 문법으로 작성하게 되면 아래와 같은 코드가 될 것이다.

<script>
export default {
  props: {
    id: Number,
    title: String,
    created: String,
    author: String,
  },
  methods: {
    savePost(postId) {
      // ..
    },
    submitForm() {
      // 구조 분해 문법 미적용
      this.savePost(this.id);

      // 구조 분해 문법 적용
      const { id, savePost } = this;
      savePost(id);
    },
  },
}
</script>

 

위와 같이 작성하게 되면 this를 매번 입력하지 않아도 되는 이점이 있다,

 

다만, 해당 데이터와 메서드가 해당 컴포넌트의 것인지, 외부에서 가져오는지 구분이 어려워지므로 사용에 유의해야한다.

 

 

v-for 디렉티브에서도 구조 분해 문법을 사용할 수 있다.

<template>
  <ul>
    <li v-for="post in posts" :key="post.id">
      {{ post.title }} - {{ post.author }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      posts: [
        { id: 1, title: "post 1", created: "2021-08-01", author: "Capt" },
        { id: 2, title: "post 2", created: "2021-08-02", author: "Capt" },
        { id: 3, title: "post 3", created: "2021-08-03", author: "Capt" },
      ],
    };
  },
}
</script>

 

수정 후 

<li v-for="{ title, author, id } in posts" :key="id">
  {{ title }} - {{ author }}
</li>
728x90