Vue - Computed Property

2023. 7. 30. 18:14·📘 Frontend/Vue

Computed(연산) Property

const app = Vue.createApp({
  data() {
    return {
      counter: 0,
      name: ''
    };
  },

  methods: {
    setName(event, lastName) {
      this.name = event.target.value;
    },
    add(num) {
      this.counter = this.counter + num;
    },
    reduce(num) {
      this.counter = this.counter - num;
      // this.counter--;
    },
    resetInput() {
      // document.querySelector('input').vlaue = '';
      this.name = '';
    },
    outputFullName() {
      if (this.name === '') {
        return '';
      }
      return this.name + ' ' + 'Schwarzmuller';
      }
    },

        // 이 부분
    computed: {
      fullName() {
        console.log('로그 찍기');
        if (this.name === '') {
          return '';
        }
        return this.name + ' ' + 'Schwarzmuller';
        }
      }
  });

app.mount('#events');

일단 연산 프로퍼티와 메서드의 중요한 차이점은 Vue가 의존성을 확인하고 그 중 하나가 변경된 경우에만 실행된다는 점입니다.

computed도 객체를 값으로 전달해서 연산합니다.

여기서도 methods 처럼 많은 함수를 정의하지만 computed에서 정의한 함수는 다른 방식으로 호출되고 실행됩니다.


computed에서 생성한 함수는 함수처럼 사용하지도않고 호출도 안하고 프로퍼티처럼 사용합니다.

그래서 연산 프로퍼티 이름은 데이터 프로퍼티를 선언할때처럼 정해야 합니다.

이제 위 코드의 computed의 fullName을 HTML코드에 데이터 프로퍼티처럼 사용가능합니다.

<p>Your Name : {{ fullName }}</p>

위 코드처럼 함수 호출을 직접적으로 하는게 아니라 포인터만 추가합니다.


저 {{ }} 안의 fullName은 Vue의 스코프에서 첫번쨰로 data의 프로퍼티로 존재하는지 확인, 없다면 computed에서 확인합니다.

이제 다시 개발자 도구에서 Counter를 증가/감소 시켜보면 모든 Vue 메서드가 재실행되지 않게 됩니다.

즉, 저 코드에서 유일한 의존성인 name 프로퍼티의 변경이 있을때만 평가가 수행되게 됩니다.

성능 면에서 값을 출력할 땐 methods보다 computed를 사용하는게 좋습니다.


methods는 페이지에서 어떤 항목이 변경되든 값을 재계산 하려는 경우에만 사용하는걸 권장합니다.

저작자표시 (새창열림)

'📘 Frontend > Vue' 카테고리의 다른 글

Vue - Methods & Computed & Watch & 축약어 정리  (0) 2023.07.30
Vue - Watcher  (0) 2023.07.30
Vue - 양방향 바인딩: v-model  (0) 2023.07.30
Vue - Event Modifier  (0) 2023.07.27
Vue - Native Event Object  (0) 2023.07.27
'📘 Frontend/Vue' 카테고리의 다른 글
  • Vue - Methods & Computed & Watch & 축약어 정리
  • Vue - Watcher
  • Vue - 양방향 바인딩: v-model
  • Vue - Event Modifier
신건우
신건우
조용한 개발자
  • 신건우
    우주먼지
    신건우
  • 전체
    오늘
    어제
    • 분류 전체보기 (422)
      • 📘 Frontend (71)
        • Markup (1)
        • Style Sheet (2)
        • Dart (8)
        • Javascript (12)
        • TypeScript (1)
        • Vue (36)
        • React (2)
        • Flutter (9)
      • 📘 Backend (143)
        • Java (34)
        • Concurrency (19)
        • Reflection (1)
        • Kotlin (29)
        • Python (1)
        • Spring (42)
        • Spring Cloud (5)
        • Message Broker (5)
        • Streaming (2)
        • 기능 개발 (5)
      • 💻 Server (6)
        • Linux (6)
      • ❌ Error Handling (11)
      • 📦 Database (62)
        • SQL (31)
        • NoSQL (2)
        • JPQL (9)
        • QueryDSL (12)
        • Basic (4)
        • Firebase (4)
      • ⚙️ Ops (57)
        • CS (6)
        • AWS (9)
        • Docker (8)
        • Kubernetes (13)
        • MSA (1)
        • CI & CD (20)
      • 📚 Data Architect (48)
        • Data Structure (10)
        • Algorithm (8)
        • Programmers (17)
        • BaekJoon (5)
        • CodeUp (4)
        • Design Pattern (4)
        • AI (0)
      • ⚒️ Management & Tool (8)
        • Git (7)
        • IntelliJ (1)
      • 📄 Document (10)
        • Project 설계 (6)
        • Server Migration (3)
      • 📄 책읽기 (2)
        • 시작하세요! 도커 & 쿠버네티스 (2)
      • 🎮 Game (4)
        • Stardew Vally (1)
        • Path of Exile (3)
  • 블로그 메뉴

    • 링크

      • Github
    • 공지사항

    • 인기 글

    • 태그

      Lock #Thread #Concurrency
      GStreamer #Pipeline
      React #Markdown
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    신건우
    Vue - Computed Property
    상단으로

    티스토리툴바