Vue.js 2

Min·2021년 3월 15일
0

Vue

목록 보기
1/1

Vue.js 2

코지 코더님의 강의를 수강후 정리한 내용입니다.
Vue 공식문서

1. 뷰 인스턴스 생성하기

  • VSCode의 Vetur 익스텐션
  • Script에 CDN 추가하는 방법 사용
<!-- 개발버전, 도움되는 콘솔 경고를 포함. -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  {{ name }} // '데이터'
</div>
<script>
  new Vue({
	el: '#app'
    data: {
      name: '데이터'
    }
})
</script>

2. 뷰 데이터(data)와 메소드(methods)

<div id="app">
  {{ nextYear('Hi') }} // 'Hi 철수 10'
</div>
<script>
  new Vue({
	el: '#app'
    data: {
      person: {
        name: '철수',
        age: '10'
      }
    },
    methods: {
      nextYear(greeting) {
        return greeting + this.person.name + this.person.age
      },
      otherMethod() {
        this.nextYear()
      }
    }
})
</script>

3. 데이터 바인딩(Data Binding)

:type='type' === v-bind:type='type'

<div id="app">
  <input :type='type' :value='inputData'>
  <a :href='link('path')'>구글링크</a>  
</div>
<script>
  new Vue({
	el: '#app'
    data: {
      inputData: 'hello',
      type: 'number',
      link: 'https://www.google.com/'
    },
    methods: {
      googleLink(path) {
        return this.link + path
      }
    }
})
</script>

4. 이벤트(Events)

이벤트 : 어떤 사건이 발생했을 때 어떤 것을 할 것인지
@click === v-on:click
form 태그는 submit을 했을 때 페이지를 리로드 한다.
공식문서의 '이벤트 핸들링 -> 참고

<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!')
          console.log('hello')
        }
    }
})
</script>

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

주석 처리된 코드와 같은 역할을 한다.

<div id="app">
  <form v-on:submit.prevent='submit'>
    // <input type='text' :value='text' @keyup='updateText'><br>
    <input type='text' v-model='text'><br>
    {{ text }}<br>
    <button type='submit'>Submit</button>
  </form>
</div>
<script>
  new Vue({
	el: '#app'
    data: {
      text: 'text'
    },
    methods: {
        submit() {
          alert('Submitted!')
          console.log('hello')
        },
        // updateText(event) {
        //   this.text = event.target.value
        // }
    }
})
</script>

6. Computed 속성

{{ 자바스크립트 문법 }}
Computed에서 하나의 로직을 처리하므로 중복제거의 효과가 있다.

methods : 함수 형식으로 사용(캐싱X)
-> 함수를 사용하려고 할때마다 계산

computed : 변수 형식으로 사용(캐싱O)
-> 처음에 한번 계산 후 저장된 값을 사용

아래 코드는 computed(reverseMessage())에서 '헬로우'를 먼저 저장하지만
click 이벤트가 실행되며 changeMessage()에서 '안녕하세요'로 덮어쓴다.

<div id="app">
  <button @click='changeMessage'>클릭</button>
  {{ reverseMessage }} // '요세하녕안'
</div>
<script>
  new Vue({
	el: '#app'
    data: {
      message: '헬로우'
    },
    methods: {
        changeMessage() {
          this.message = '안녕하세요'
        }
    },
    computed: {
      reverseMessage() {
        return this.message.split('').reverse().join('')
      }
    }
})
</script>

7. Watch 속성

Computed 속성을 사용할 수 없을 때 Watch 속성을 사용하는 것이 좋다.
Watch 속성은 newVal와 oldVal를 파라미터로 받는다.

<div id="app">
  {{ message }}
  <button @click='changeMessage'>클릭</button><br>
  {{ updated }}
</div>
<script>
  new Vue({
	el: '#app'
    data: {
      message: '헬로우',
      updated: '아니요'  
    },
    methods: {
        changeMessage() {
          this.message = '안녕하세요'
        }
    },
    computed: {
      reverseMessage() {
        return this.message.split('').reverse().join('')
      }
    },
    watch: {
      message(newVal, oldVal) {
        console.log(newVal, oldVal) // 요세하녕안 네
        this.updated = '네'
      }
    }  
})
</script>

8. 클래스 & 스타일 바인딩

  1. 클래스 바인딩
<style>
  .red {
    color: red
  }
  font-bold {
    font-weight: bold
  }
</style>

<div id="app">
  <div :class='{ red: isRed, 'font-bold': isBold}'>헬로우</div>
  <button @click='update'>클릭</button>
</div>
<script>
  new Vue({
	el: '#app'
    data: {
      isRed: false,
      isBold: false  
    },
    methods: {
        update() {
          this.isRed = !this.isRed
          this.isBold = !this.isBold
        }
    }
})
</script>
profile
slowly but surely

0개의 댓글