본문 바로가기
front-end/vue.js

처음 시작하는 Vue.js(3), 뷰 HTTP 통신과 데이터 바인딩

by MOOB 2019. 9. 14.

  • HTTP : 브라우저와 서버간에 데이터를 주고받는 통신 프로트콜
    뷰에서는 이를 지원하기 위해 axios를 리소스를 지원한다.

뷰 리소스 방식

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="app">
       <button v-on:click="getData">프레임워크 목록 가져오기</button>
     </div>

     <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
     <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.3.4"></script>
     <script>
       new Vue({
         el: '#app',
         methods: {
           getData: function() {
             this.$http.get(`https://raw.githubusercontent.com/joshua1988/doit-vuejs/master/data/demo.json`)
                 .then(function(response) {
                   console.log(response);
                   console.log(JSON.parse(response.data));
                 });
           }
         }
       });
     </script>
  </body>
</html>

뷰 리소스가 1.5.2 버전인 현재는 위와 같이 하면 에러가 발생한다. ES6문법에 맞춰 다음과 같이 사용하자. 더 직관적인가? 잘 모르겠다.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="app">
       <button v-on:click="getData">프레임워크 목록 가져오기</button>
     </div>

     <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
     <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.3.4"></script>
     <script>
       new Vue({
         el: '#app',
         methods: {

           getData: function() {
           this.$http.get('https://raw.githubusercontent.com/joshua1988/doit-vuejs/master/data/demo.json').then(response => {
             console.log(response);
             console.log(JSON.parse(response.data));
             });
           }

         }
       });
     </script>
  </body>
</html>

엑시오스 방식

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="app">
       <button v-on:click="getData">프레임워크 목록 가져오기</button>
     </div>

     <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
     <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
     <script>
       new Vue({
         el: '#app',
         methods: {

           getData: function() {
           axios.get('https://raw.githubusercontent.com/joshua1988/doit-vuejs/master/data/demo.json').then(response => {
             console.log(response);
             });
           }

         }
       });
     </script>
  </body>
</html>

Data 속성이 일반 문자열이 아닌 객체 형식이기 때문에 별도로 JSON.parse()를 사용할 필요가 없다.

데이터 바인딩

  • 데이터 바인딩 : html 화면 요소를 뷰 인스턴스와 데이터에 연결하는 것을 의미한다.
  • v-once : 뷰 데이터가 변경되어도 값을 바꾸고 싶지 않을 때 사용함
  • v-bind : 아이디, 스타일, 클래스 등의 html 속성 값에 뷰 데이터 값을 연결할 대 사용함.
<div id = "app">
    <p v-bind:id="hello">hello</p>
</div>
<script>
  new Vue({
    el:'#app'
  data:{
    hello:'color:green'
}
)}
</script>

자바스크립트 표현식과도 혼용해서 사용이 가능함. 왠지 모르지만 반영이 좀 늦다.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="app">
       <p>{{message.split('').reverse().join('')}}</p>
     </div>

     <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
     <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
     <script>
       new Vue({
         el: '#app',
         data: {
           message : 'hello how are you!'
         }
       });
     </script>
  </body>
</html>

다만 위와 같은 경우 복잡한 연산은 인스턴스에서 해결하는 것이 적절함. 또한 선언문 분기 구문등은 사용할 수 없음. 인스턴스 엄청 오래 걸리는데요…

computed 속성과 methods 속성의 차이

Methods 속성은 호출할 때만 해당 로직이 수행되고 computed 속성은 대상 대에터 값이 변경되면 자동으로 수행되며 캐싱을 사용한다.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="app">
       <p>{{hellothing}}</p>
     </div>

     <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
     <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
     <script>
       new Vue({
         el: '#app',
         data: {
           message : 'hello how are you!'
         },
         computed:{
           hellothing:function(){
             return this.message.split('').reverse().join('');
           }
         }
       });
     </script>
  </body>
</html>

뷰 디렉티브

  • v-if : 지정한 뷰 데이터 값의 참, 거짓 여부에 따라 해당 html 태그를 화면에 표시하거나 표시하지 않음
  • v-for : 지정한 뷰 데이터의 갯수만큼 해당 html 태그를 반복 출력함
  • v-show : 데이터의 진위 여부에 따라 해당 html 태그를 표시하거나 표시하지 않음. 단 이 경우는 css효과를 통해 display:none이 됨
  • v-on : 이벤트 처리 시 사용, v-on:click="event(10)"과 같은 방식으로 인자 값을 넘길 수 있음. function(event)를 정의하면 이벤트 객체에 접근할 수 있은.
  • v-model : form에서 주로 사용되는 속성. 폼에 입력한 값을 뷰 인스턴스의 데이터와 즉시 동기화 함
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="app">
       <p v-if="flag">hello</p>
       <p v-for="item in items">{{item}}</p>
       <button v-on:click="alert">button</button>
     </div>

     <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
     <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
     <script>
       new Vue({
         el: '#app',
         data: {
           flag: true,
           items: ['hello', 'world', 'how', 'are', 'you']
         },
         methods:{
           alert: function(){
             return alert('경고창입니당');
           }
         }
       });
     </script>
  </body>
</html>

watch 속성

데이터 뱐화를 감지하여 자동으로 특정 로직을 수행한다. computed속성과 유사하지만 데이터 호출과 같은 시간이 더 소모되는 작업에 적합하다.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="app">
       <input v-model="message">
     </div>

     <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
     <script>
       new Vue({
         el: '#app',
         data: {
           message: 'hello world'
         },
         watch:{
           message:function(data){
             console.log("message changed : ", data);
           }
         }
       });
     </script>
  </body>
</html>

댓글