[Vue] - Basic 속성

배정규·2020년 8월 22일
0

vue

목록 보기
1/7

v-bind

  • data 를 바인딩 해준다.
  • v-bind 대신 :(콜론) 으로 축약해서 사용 가능
  • data, methods 키값을 this.키값으로 사용
  • 대부분의 html 속성에 적용 가능하다.

v-on

  • 이벤트를 사용할 수 있다.
<body>
  <div id="app">
    {{year}} <br>
    <button @click="plus">더하기</button>      // v-on: 을 @로 축약해서 사용가능
    <button v-on:click="minus">빼기</button>	// script 안에 methods 에 있는 함수들을 "" 안에 넣어서 사용한다.
  </div>
  <script>
    new Vue({
      el: '#app',
      data: {
        year: 2020
      },
      methods: {
        plus() {
          this.year++;
        },
        minus() {
          this.year--;
        }
      }
    })
  </script>
</body>

prevent

<body>
  <div id="app">
    <form @submit.prevent="submit">       // 이런식으로 prevent 를 사용
      <button type="submit">Submit</button>
    </form>
  </div>
  <script>
    new Vue({
      el: '#app',
      data: {
        year: 2020
      },
      methods: {
        submit() {
          alert("완료!")
          console.log("hello")
        }
      }
    })
  </script>
</body>

v-model

  • 데이터 양방향 바인딩
  • 주석처리한 부분을 v-model 로 사용할 수 있다.
<body>
  <div id="app">
    <form @submit.prevent="submit">
      <!-- <input type="text" :value="message" @keyup="updateMessgae"><br> -->
      <input type="text" v-model="message"><br>
      {{message}} <br>
      <button type="submit">Submit</button>
    </form>
  </div>
  <script>
    new Vue({
      el: '#app',
      data: {
        message: 'text',
      },
      methods: {
        submit() {
          alert("안녕하세요?")
          console.log("hello")
        },

        // updateMessgae(e) {
        //   this.message = e.target.value;
        // }
      }
    })
  </script>
</body>

computed

  • 복잡한 연산을 사용할 때 computed 속성을 사용한다.
  • computed 속성을 사용했을 때 장점은 유지보수와 성능개선이다.
  • methods 에서 넣어 동일하게 사용할 수도 있지만, 매소드에서 사용할 경우 사용하는 개수 만큼 함수를 호출해줘야하기 때문에 많은 데이터를 처리할 때 성능문제가 발생한다.
  • computed 는 계산 결과를 저장하고 있기 때문에 여러 번 요청을 해도 계산을 다시 하지 않고 이미 계산되어 있던 결과를 즉시 반환한다.
  • 더 자세한 내용은 Vue.js 공식 문서 확인
<body>
  <div id="app">
    <button @click="changeMessage">Click</button>
    {{ reverseMessage }}
    {{ reverseMessage }}
    {{ reverseMessage }}
  </div>
  <script>
    new Vue({
      el: '#app',
      data: {
        message: '헬로우',
      },
      methods: {
        changeMessage() {
          this.message = '위코드';
        }
      },
      computed: {
        reverseMessage() {
          return this.message.split('').reverse().join('')
        },
      }
    })
  </script>
</body>

class & style binding

  • 클래스 바인딩
<style>
    .red {
      color: red;
    }

    .font-bold {
      font-weight: bold;
    }
  </style>
</head>

<body>
  <div id="app">
    <div :class="{ red: isRed, 'font-bold': isBold }">Hello</div>
    <button @click="update">Click</button>
  </div>
  <script>
    new Vue({
      el: '#app',
      data: {
        isRed: false,
        isBold: false,
      },
      methods: {
        changeMessage() {
          this.message = '위코드';
        },
        update() {
          this.isRed = !this.isRed;
          this.isBold = !this.isBold;
        }
      }
    })
  </script>
  • 스타일 바인딩

<style>
    .red {
      color: red;
    }

    .font-bold {
      font-weight: bold;
    }
  </style>
</head>

<body>
  <div id="app">
    <div :style="{ color: red, fontSize: size}">Hello</div>
    <button @click="update">Click</button>
  </div>
  <script>
    new Vue({
      el: '#app',
      data: {
        red: 'red',
        size: '30px',
      },
      methods: {
        changeMessage() {
          this.message = '위코드';
        },
        update() {
          this.isRed = !this.isRed;
          this.isBold = !this.isBold;
        }
      }
    })
  </script>
</body>

v-if & v-show

  • v-if 디렉티브는 조건에 따라 블록을 렌더링하기 사용, 블록은 디렉티브의 표현식이 true 값을 반환할 때만 렌더링됨
  • v-if 는 초기 렌더링에서 조건이 거짓이면 아무것도 렌더링하지 않는다.
  • 조건 블록이 처음으로 참이 될 때까지 렌더링되지 않는다.
  • v-show 는 초기 조건에 상관없이 항상 렌더링 된다.
  • 그래서 v-if 는 토글 비용이 높고, v-show 는 초기 렌더링 비용이 높다.
  • 매우 자주 바뀌기를 원하면 v-show, 런타임 시 조건이 바뀌지 않으면 v-if 권장
<body>
  <div id="app">
    <!-- <template v-if="number === 1">
      <div>1</div>
      <div>2</div>
      <div>3</div>
    </template>
    <div v-else-if="number === 2">hi</div>
    <div v-else>No</div> -->
    <div v-show="show">Yse</div>
    <br>
    <button @click="toggle">Toggle</button>
  </div>
  <script>
    new Vue({
      el: '#app',
      data: {
        number: 1,
        show: false
      },
      methods: {
        increaseNumber() {
          this.number++;
        },
        toggle() {
          this.show = !this.show
        }
      }
    })
  </script>
</body>

v-for 리스트 렌더링

  • v-for 를 사용하여 반복적인 코드를 제거하여 효율적으로 리스트를 렌더링할 수 있다.
  • 리스트를 생성할 때는 고유한 key 값을 제공해주어야 한다.
<body>
  <div id="app">
    <div> // 반복적인 코드의 예시
      {{people[0].name}} {{ people[0].age}}
    </div>
    {{people[1].name}} {{ people[1].age}}
    <div>
      {{people[2].name}} {{ people[2].age}}
    </div>
    <div>
      {{people[3].name}} {{ people[3].age}}
    </div>

    <hr>
	// v-for 사용 예시 
    <div v-for="(person, index) in people" key="person.id"> // 두 번째 인자로 index 를 가져올 수도 있다. 
      {{person.name}} {{ person.age}} {{index}}
    </div>
  </div>
  <script>
    new Vue({
      el: '#app',
      data: {
        people: [
          { id: 1, name: 'a', age: 20 },
          { id: 2, name: 'b', age: 23 },
          { id: 3, name: 'c', age: 22 },
          { id: 4, name: 'd', age: 24 },
          { id: 5, name: 'e', age: 26 },
        ],
      },
      methods: {

      },
    })
  </script>
</body>
profile
Seize the day

0개의 댓글