TIL_Vue.js(1)

김진경·2020년 6월 4일
0

IM19

목록 보기
18/21

6/3 Vue.js 기본강좌 요약정리.

[1] 인스턴스 생성하기

Vue.js는 프로그레시브 프레임워크라고 한다. 기존 프로젝트를 Vue.js로 전환하고 싶을 때 새로 다시 만들 필요가 없다. 부분 부분을 업데이트하며 전환할 수 있다.

  • 직접 script에 추가 가능
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  • CLI 이용 가능.
  • vetur 익스텐션 설치.

인스턴스 생성

<div id="app"></div>
<script>
  new Vue({
    el: '#app'
  })
</script>

위와 같이 Vue 인스턴스를 생성한다.
이제 app이라는 아이디의 태그 안에 Vue 코드를 작성할 수 있다.

[2] 데이터(data)와 메소드(methods)

데이터(data:{}) 사용

중괄호 두번으로 화면에 출력 하고
data 안의 person이라는 변수에서 데이터를 가져온다

<div id="app">
{{ person.name }}{{ person.age }}
</div>
<script>
    new Vue({
    	el: '#app',
        data: {
            person:{
            name: '코지 코더',
            age: 34
            }
        },
    })
</script>

메서드(methods:{}) 사용

메서드 안에선 함수를 만들어 사용할 수 있다.
div안의 2중 괄호 안에서 사용할 때 ()를 붙여야 실행이 된다.
메서드 안에선 어느 함수(otherMethod)가 다른 함수(nextYear)를 가지고 오는 것도 가능하다.

<div id="app">
{{ nextYear('안녕!) }}
</div>
<script>
	new Vue({
          el: '#app',
          data: {},
          methods: {
            //nextYear: funciton(greeting). 아래와 같은 방식으로 생략 가능.
            nextYear: (greeting){
            	return this.person.name + ' 는 내년에 ' + (this.person.age + 1) + '살 입니다';
             }
             otherMethod{
             	this.nextYear();
             }
           }
    	})
</script>

[3] 데이터 바인딩(data binding)

(v-bind) : 데이터를 해당 태그에 바인딩 시켜주는 태그이다.
v-bind는 생략하고 : 만 사용할 수 있다.
methods에 작성된 함수를 삽입할 수도 있다.
ex):href="getKossieCoderLink('kossiecoder')"

<div id="app">
  {{ nextYear('안녕!) }}
  <!--input v-bind:type="number" v-vind:value="inputData"-->
  <input :type="number" :value="inputData">
  <a :href="getKossieCoderLink('kossiecoder')">코지 코더 채널</a>
</div>
<script>
	new Vue({
          el: '#app',
          data: {
            person:{
            	name: '코지 코더',
            	age: 34
            }
            inputData: 'hello',
            type: 'number',
            link: 'https://www.youtube.com/kossiecoder'
          },
          methods: {
          	getKossieCoderLink(channel){
                   return this.link + channel
          }
        )}
</script>

[4] 이벤트(Events)

v-on:click = click에 이벤트를 걸어놓음.

<div id="app">
  {{ year }}<br>
  <button v-on:click="alert">더하기</button>
  <button v-on:click="alert">빼기</button>
</div>
<script>
	new Vue({
          el: '#app',
          data: {
            year: 2018
          },
          methods: {
            plus(){
              this.year++;
            },
            minus(){
              this.year--;
            }
          }
        )}
</script>

_다른 예제. 버튼을 누르면 submitted를 alert으로 띄움.
v-on:submit=submit에 이벤트를 걸어놓음.
form 태그sms submit을 하고 나오는 알럿창을 ok했을 때 페이지를 리로드한다(console.log('hello')가 빠르게 사라지는 것으로 알 수 있음).
그것을 .prevent를 뒤에 붙임으로써 막을 수 있다.

<div id="app">
  <form v-on:submit.prevent="submit">
    <input type="text"><br>
    <button type="submit">Submit</button>
  </form>
</div>
<script>
	new Vue({
          el: '#app',
          data: {
          },
          methods: {
            submit(){
               alert('submitted');
            }
          }
        )}
</script>

[5] 데이터 양방향 바인딩(Data Two Way Binding v-model)

v-model="태그"
입력칸에 텍스트를 치는 대로 {{text}}에도 같은 내용이 입력됨.

<div id="app">
  <form v-on:submit.prevent="submit">
    <input type="text" v-model="text"><br>
    {{ text }}<br>
    <button type="submit">Submit</button>
  </form>
</div>
<script>
	new Vue({
          el: '#app',
          data: {
             year:2018,
             text: 'text'
          },
          methods: {
          }
        )}
</script>

[6] Computed 속성

만약 아래의 {{}}의 안에 많은 연산이 들어간다고 가정해보자. 코드가 비대해지고 가독성이 떨어질 것이다. 이때 Computed 속성을 사용하면 '미리 계산해두기' 때문에 훨씬 효율적인 코드 작성이 가능하다. 이때 methods에 함수를 작성해서 사용하는 것과 뭐가 다른가? 하는 질문이 생길 수 있다.

차이점은 computed 속성은 종속 대상을 따라 저장(캐싱)된다는 것이다. computed 속성은 해당 속성이 종속된 대상이 변경될 때만 함수를 실행한다. 즉, message가 변경되지 않는 한, computed 속성인 reversedMessage를 여러 번 요청해도 계산을 다시 하지 않고 계산되어 있던 결과를 즉시 반환한다.

캐싱이 왜 필요할까? 계산에 시간이 많이 걸리는 computed 속성인 A를 가지고 있다고 해보자. 이 속성을 계산하려면 거대한 배열을 반복해서 다루고 많은 계산을 해야 한다. 비동기적 렌더링이 필요한 상황에서 느린 반응은 약점을 다가올 수 있다.

<div id="app">
  <button @click="changeMessage">Click</button>
  {{ reversedMessage }}
  {{ reversedMessage }}
  {{ reversedMessage }}
</div>
<script>
	new Vue({
          el: '#app',
          data: {
             message: '헬로우'
          },
          methods: {
             changeMessage(){
                this.message = '코지코더'
             }
          },
          computed: {
             reversedMessage(){
                return this.message.split('').reverse().join('')
             }
          }
        )}
</script>

[7] Watch 속성

watch의 대상이 되는 태그는 새로 업데이트 된 값(newValue)과, 업데이트 되기 전의 값(oldVal)을 인자로 받는다.

watch속성은 대상 태그에 변화가 생기면 대상 태그의 함수를 실행하도록 한다.

아래 코드는 버튼 클릭으로 인해 다음과 같은 변화를 보여준다.

헬로우(watch의 감시 대상인 message 태그의 값)
--클릭시--> changeMessage 함수로 인해 '코지코더'로 바뀜

아니요 --> 감시 대상인 message에 변화가 생겼고 watch 속성으로 인해
message의 함수(this.updated) 가 실행됨

<div id="app">
  {{ message }}<br>
  <button @click="changeMessage">Click</button><br>
  {{ updated }}
</div>
<script>
	new Vue({
          el: '#app',
          data: {
             message: '헬로우',
             updated: '아니요'
          },
          methods: {
             changeMessage(){
                this.message = '코지코더'
             }
          },
          computed: {
             reversedMessage(){
                return this.message.split('').reverse().join('')
             }
          },
          watch: {
             message(newVal, oldVal){
                 console.log(newVal, oldVal);
                 this.updated = '네';
             }
          }
        )}
</script>

[8] 클래스 & 스타일 바인딩

_클래스 바인딩
:class="{스타일의 변수(: data의 변수) 스타일의 변수(: 데이터의 변수)...}"
스타일태그 중간에 하이픈(-)이 들어가있을 경우 ''로 감싸준다.
ex) { red: isRed, 'font-bold': isBold }

 <style>
    .red {
      color: red;
    }
    .font-bold {
      font-weight: bold;
    }
  </style>
  <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: {
          update(){
            this.isRed = !this.isRed;
            this.isBold = !this.isBold;
          }
        }
      });
    </script>
  </body>

_스타일 바인딩
:style="{스타일인자: data의 변수, 스타일인자: data의 변수...}"
클래스와 다른 점은 클래스는 ': 데이터의 인자' 가 생략돼도 된다.

 <style>
    .red {
      color: red;
    }
    .font-bold {
      font-weight: bold;
    }
  </style>
  <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: {
          update(){
            this.isRed = !this.isRed;
            this.isBold = !this.isBold;
          }
        }
      });
    </script>
  </body>

[9] v-if와 v-show

_v-if

v-if는 조건부 블럭 안의 이벤트 리스너와 자식 컴포넌트가 토글하는 동안 적절하게 제거되고 다시 만들어지기 때문에 “진짜” 조건부 렌더링이다.

v-if는 또한 게으르다. 초기 렌더링에서 조건이 거짓인 경우 아무것도 하지 않는다. 조건 블록이 처음으로 참이 될 때 까지 렌더링 되지 않는다.

  <body>
    <div id="app">
      <div v-if="show">Yes</div>
      <div v-else-if="">Hi</div>
      <div v-else>No</div>
      <br>
      <button @click="toggleShow">Toggle</button>
    </div>
    <script>
      new Vue({
        el: '#app',
        data: {
           show: false 
        },
        methods: {
           toggleShow(){
              this.show = !this.show;
           }
        }
      });
    </script>
  </body>

_v-show

v-show는 훨씬 단순하다. CSS 기반 토글만으로 초기 조건에 관계 없이 엘리먼트가 항상 렌더링된다.

일반적으로 v-if는 토글 비용이 높고 v-show는 초기 렌더링 비용이 더 높다. 매우 자주 바꾸기를 원한다면 v-show를, 런타임 시 조건이 바뀌지 않으면 v-if를 사용하는 것이 좋다.

  <body>
    <div id="app">
      <div v-show="show">Yes</div>
      <button @click="toggleShow">Toggle</button>
    </div>
    <script>
      new Vue({
        el: '#app',
        data: {
           show: false
        },
        methods: {
           toggle(){
              this.show = !this.show;
           }
        }
      });
    </script>
  </body>

출처
https://kr.vuejs.org/v2/guide/
https://www.youtube.com/channel/UCI4tTBupvhMX1aWDSm-HAXw

profile
Maktub.

0개의 댓글