[KDT]FCFE - 6주5일 vue ( lifecycle,)

Keunyeong Lee·2022년 1월 3일
0

vue

lifecycle hook

beforeCreated, created, mounted, updated, unmounted

  • created, mounted 를 많이 활용한다.

  • created 는 컴포넌트를 생성한 직후이다.

  • mounted 는 html에 연결된 직후이다.

template 문법

보간법

  • {{ msg }} 와 같이 사용한다.

  • v-once 라는 디렉티브를 사용하면 데이터가 변하더라도 처음 한번 뿌려진 이후에는 갱신되지 않는다.

computed

  • 메소드를 넣어 return 으로 계산된 형태를 사용할 수 있다.
  • 연산이 되어있는 상태로 저장된 캐싱 기능을 사용할 수 있다.
computed: {
  reversedMessage: {
    get(){
      return this.masg.split('').reverse().join('')
    },
    set(value){
      this.msg = value
    }
  }
},
methods: {
  add(){
   this.reversedMessage += '!?'
  }
}

watch

  • data를 감시하고 있다가 변경되면 실행된다.

  • method 인자로 변경된 data값이 들어온다.

클래스와 스타일 바인딩

  • v-bind:class="{ active: isActive }" @click="activate"

  • isActive 가 true 면 클래스에 active 추가.

  • html 의 class 이름은 dash-case, snake_case 를 사용해야 한다.

<div :class="classObject"></div>
data(){
  return {
    classObject: {
      active:true,
      'text-danger': false,
    }
  }
}
data(){
  return {
    active: true,
    error: null,
  }
},
computed : {
  classObject(){
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'false'
    }
  }
}

조건문

  • if문을 통해 조건문 작성.

  • template 태그를 이용하면 if문을 묶어서 구성할 수 있고 html에는 노출되지 않도록 할 수 있다.

<template>
  <button @click="handler">
    Click me!
  </button>
  <template v-if="isShow">
    <h1>Title</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
  </template>
</template>
<script>
export default {
  data(){
    return {
      isShow: true,
      count:0
    }
  },
  methods: {
    handler(){
      this.isShow = !this.isShow
      this.count += 1
    }
  }
 }
}
</script>

v-if vs v-show

  • v-show는 falsy 의 경우 display:none 상태로 보이지 않게 한다.

  • v-show는 template에 사용하여 보이지 않도록 할 수 없다.

  • v-if 는 실제 조건부 렌더링으로 값이 falsy의 경우 아무것도 렌더링 되지 않는 것을 의미한다.

  • v-if 는 전환비용이 높고, v-show 는 초기 렌더링 비용이 높다.

  • 자주 전환이 필요하다면 v-show ( 토글 )

  • 런타임 시 조건이 변경되지 않는다면 v-if ( page )

profile
🏃🏽 동적인 개발자

0개의 댓글