Vue.js 기본 가이드

이재원·2021년 8월 5일
0

data

data에 프로퍼티나 객체를 추가하여 template에 태그를 추가하여 태그안에서 {{ }} 사용하여 data 변수에 선언된 값을 출력 할 수 있다.

<template>
  <div id="app">
    {{person.name}}  
    {{person.age}}
  </div>
</template>

<script>
export default {
  name: 'App',
  components: {
  },
 
  data(){
    return{
        person:{
          name:'Jaewon',
          age: 100
        }
    }
  }, 
}
</script>

methods 사용

  1. methods 프로퍼티에 함수를 선언하여 사용 script내에서 data 나 함수를 사용하려면 this. 사용하여 호출해야 한다.
    예) script에서 사용시 this.personInfo, this.person.age
  2. template에서는 this. 사용하지 않고 {{}}에 data에 선언된 프로퍼티나 methods의 함수를 사용 할 수 있다.
    예) template에서 사용 시 {{personInfo()}} , {{this.person.age}}
<template>
  <div>
    <p>{{personInfo()}}</p>
    <p>{{showPerson()}}</p>
    <p>{{otherPerson(person)}}</p>
  </div>
</template>

<script>
  export default {    
    data(){
      return{
          person:{
            name:'이재원',
            age: 100,
          }
      }
    }, 

    methods:{
      personInfo(){ 
        return '이름은:'+ this.person.name+ '이며 나이는:'+this.person.age;
      },
      showPerson: function(){
          return this.personInfo();
      },
      otherPerson:(person)=>{
          return '이름은:'+ person.name+ '이며 나이는:'+person.age;          
      }
    }
  }
</script>

v-once

v-once를 선언한 태그에서사용하는 데이터는 값을 변경해도 처음에 한번 설정 된 값을 유지한다.
changename() 함수를 호출하여 name의 값을 변경해도 변경되지 않는다.

<template>
  <div>    
    <p v-once>{{name}}</p>
    <button  :class="classStatus" @click="changeName()"></button>
  </div>
</template>

<script>
export default {
  data(){
    return {
      name:'뷰JS'
    }
  },
  methods:{
    changeName(){
      this.name='자바스크립트';
    }
  }
}
</script>

v-html (태그추가)

div태그 속성에 v-html에 태그를 문자열로 전달하면 div태그 하위에 태그들이 만들어진다.

<template>
  <div>    
    <div v-html="insertTag"></div>
  </div>
</template>

<script>
export default {
  data(){
    return {
      insertTag:'<h1>태그 삽입 합니다.</h1>'+
                '<h2>태그 삽입 합니다.</h2>'+
                '<span>aaa</span><span>bbbb</span> ',
    }
  },
}
</script>

v-bind: ,단축문법-> : (class,href,type,value 등의 속성 변경)

  1. bind할 속성 값을 앞에 v-bind: 를 붙여서 사용하며 :속성 값으로 줄여서 사용이 가능 하다
  • v-bind:type=""
  • :type=""
  • :href=""
  • :class=""
  1. class bind 할 경우
    div 테그에 기존 class에 static이 있으며 isActiv와 hasError의 값이 true, false에 따라 div의 class 속성에 active와, text-danger 활성화 하여 Style의 값을 적용 할 수 있다
// 단일 hasError 값이 TRUE이면 현재 태그에 text-danger 추가함
<template>
  <div>
    <input type="number" value="ddddddd">
    <a href="https://www.naver.com">네이버</a>

    <input v-bind:type="inputType" v-bind:value="inputValue">
    <a v-bind:href="link">네이버</a>

    <input :type="inputType" :value="inputValue">
    <a :href="link">네이버</a>

    <div class="box"></div>
    <div v-bind:class="classValue"></div>
    <div :class="{box:showBox}"></div>
    <div :class="{box: showBox , 'box-container': showBoxContainer}"></div>    
    <div :class="boxClassObject"></div>    
  </div>  
</template>

<script>
  export default {    
    data(){
      return{          
          inputType:"number",
          inputValue: 10000000,
          link:'https://www.naver.com',
          showBox:true,
          showBoxContainer:false,
          boxClassObject:{
            box:true,
            'box-container':false
          },
          classValue:'title',
      }
    }, 
  }
</script>

v-on: , 단축문법 ->@ (이벤트 연결)

  1. v-on은 Event를 핸들링 하기위해 사용 한다 click 이벤트를 핸들이한다고 하면 아래 와 같이 사용이 가능 하다
  • v-on:click=""
  • @click="" 줄여서 표현
  1. 이벤트 참조 사이트
<template>
  <div>
    <p>{{age}}</p>

    <button v-on:click="plus()">plus</button>    
    <button @click="minus()">minus</button>    
    <button @click.once="minus()">minus</button>    

    <input v-on:keyup.enter="minus()">
    <input @keydown.page-down="minus()">
      
  </div>  
</template>

<script>
  export default {    
    data(){
      return{          
        age:0
      }
    }, 
    methods:{
      plus(){
        this.age++;
      },
      minus(){
        this.age--;
      }      
    }
  }
</script>

computed (캐싱기능)

computed를 사용하여 연산이 오래걸리는 데이터에 대해서 캐싱 작업을 할수 있다
한번 연산 후 해당 연산을 하지 않고 자동으로 변수만 반환하여 성능을 향상할 수 다.
1. template에서 호출시 ()를 적지 않아야 된다.
2. return 값이 반드시 존재해야한다.
3. 파라메터를 받을 수 없다.

4. 속성에서 사용가능

<template>
  <div>
    <p>{{getname}}</p>
  </div>
</template>

<script>
export default {
  data(){
    return {
      name:'j-j-won'
    }
  },
  computed:{
    getname(){        
      return this.name.replaceAll('-','');
    },
  }
}
</script>

watch (데이터 변경 감지)

data()에 선언된 object나 프로퍼티에 대해서 watch에서 변경을 감지하기 위한 기능이다. 아래 사용방법은 3가지 형태로 제공된다.

<template>
  <div>    
    <button @click="changeName()"></button>
  </div>
</template>

<script>
export default {
  data(){
    return {
      name:'',
      music:{
        name:'',
        time:'',
        count:1
      },
      message:'',
      title:''
    }
  },
  methods:{
    changeName(){
      this.music.name="가시";
      this.music.time="3:30";      
      this.music.count++;
      this.message='테스트 입니다.';
      this.name="jaewon";
    },

    showMessage(value){
      console.log('message='+value);
    }
  },
  watch:{
    //단축 문법
    name(newValue,oldValue){
      console.log('new name=',newValue);
      console.log('old name=',oldValue);      
    },

    message:'showMessage', //함수이름을 문자로 넣으면 message 내용이 변경되면 함수가 실행됨

    title:{
        handler(newValue,oldValue){
        console.log('new title='+newValue);
        console.log('old title='+oldValue);      
      }      
    },
   
    //풀어쓰기 문법 
    music:{   
      deep:true, //중첩된 값이 변경되는 것을 확인하기 위해서는 deep옵션을 사용 해야 한다.      
      immediate: true, // 페이지 로드시 값이 변경되는것과 상관 없이 handler를 수행
      handler(newValue,oldValue){
        console.log('new music='+newValue);
        console.log('old music='+oldValue);      
      }          
    }

  	// 글로벌 프로퍼티 추가 시 '' 감싸서 사용 
    '$store.state.key'(){
		console.log('old music='+oldValue);      
  	 }  
  }
}
</script>

v-if and v-show (조건에 따른 태그 추가)

  1. v-if else if else html 태그 안에서 조건에 해당 하지 않는 if문에 대한 태그는 body 태그안에 추가 되지 않는다.
  2. v-show style의 display를 none로 처리하여 body안에 태그는 존재 한다.
<template>
    <div class="box">
     <!-- v-if else if else  html 태그 안에서 조건에 해당 하지 않는 if무은 제거됨.-->
        if 조건 입력 <input type="text" v-model="inputValue">
        <div v-if="inputValue=='동물'">
            <p>사자</p>
            <p>호랑이</p>
        </div>
        <div v-else-if="inputValue=='곤충'">
            <p>잠자리</p>
            <p>사슴벌레</p>
        </div>
        <div v-else>
            <p>동물이나 곤충 값을 입력해야 해요</p>
        </div>

        <div v-show="true">
            <p>show true</p>            
        </div>

        <!-- v-show true면 보여주고 false 안보여줌  style의 display를 none로 처리함  -->
        <div v-show="false">
            <p>show false</p>            
        </div>

    </div>    
</template>

<script>
export default {
    data(){
        return {
            inputValue:'',
        }
    }, 
}
</script>

v-for (for문을 이용하여 태그를 반복적으로 만들 수 있음)

태그에 v-for를 추가하여 현재추가한 태그를 반복적으로 추가 할 수 있다.

<template>
    <div class="box">        
        <h1>장볼 리스트</h1>
        <ul>
            <li v-for="item in list">{{item}}</li>
        </ul>
        <ul>
            <li v-for="(item,index) in travelList">{{item.name}}->{{item.distance}}</li>
        </ul>
        <ul>
            <li v-for="(item,index) in travelList" :key="index">{{item.name}}->{{item.distance}}</li>
        </ul>          
    </div>    
</template>

<script>
export default {
    data(){
        return {
            list: ['소갈비', '감자', '당근', '무', '깐 밤', '소갈비찜 양념'],
             travelList:[
                    {name: '강릉', distance: '차로 3시간'},
                    {name: '부산', distance: '차로 5시간'},
                    {name: '춘천', distance: '차로 2시간'},
                    {name: '대만', distance: '비행기로 3시간'},
                    {name: '필리핀', distance: '비행기로 5시간'},
                    {name: '스페인', distance: '비행기로 17시간'},
                ]            
        }        
    }, 
}
</script>

Compoents(vue를 재사용 할 수 있다)

사용할 vue 파일을 import 후 해당 이름을 components: 프로퍼티에
'test-a':Test, , TestCompoents 와 같이 선언 후 template에 선언하여 사용한다.

TestCompoents => test-compoents 변경하여 template에 사용 가능

<template>
  <div id="app">        
    <test-a></test-a>
    <TestCompoents></TestCompoents>
    <test-compoents></test-compoents>
  </div>
</template>

<script>
import Test from '../src/components/HelloWorld.vue'
import TestCompoents from '../src/components/TestComponents.vue'
export default {
  name: 'App',
  components: {    
    // Landingpage
    'test-a':Test,
    TestCompoents
  }
}
</script>

props (상위 컴포넌트에서 하위 컴포넌트로 데이터를 전달 받을때 사용)

TestCompoents에 받을 데이터를 props: 에 선언 후 type, required, default 값을 선언 하여 사용할 수 있다
type은 String,Number,Boolean 데이터 타입이다.

props:['address'] 와 같이 선언 할 수도 있으며 address를 와 같이
상위 컴포넌트로 부터 받을 수있다 .

----------------------------------------부모 컴포넌트 ----------------------------------------
<template>
  <div id="app">            
    <TestCompoents :title="title" name="Jaewon"  ></TestCompoents>    
  </div>
</template>

<script>
import TestCompoents from '@/components/TestComponents.vue'
export default {
  name: 'App',
  components: {        
    TestCompoents
  },
  data(){
    return{
      title:"자기소개"
    }
  }
}
</script>

----------------------------------자식 컴포넌트 TestCompoents ----------------------------------
<template>
  <div>
      <h1>{{title}}</h1>
      <h4>{{showName()}}</h4>
      <h4>{{age}}</h4>      
  </div>
</template>

<script>
export default {
    props:{
        title:{
            type : String,
            required: true  // 필수로 title을 전달 받아야하면 true 설정
        },
        name:String,
        age:{
            type : Number,
            default :55  // 기본값 지정
        }
    },
    methods:{
        showName(){
            return this.name;
        }
    }    
}
</script>

$emit (자식 컴포넌트에서 부모 컴포넌트로 이벤트 및 데이터 전달할 때 사용)

자식 컴포넌트인 TestCompoents에서 부모 컴포넌트의 template에 선언된 TestCompoents 태그로 event를 발생시킬 emit를 선언 하여 사용한다.

자식 컴포넌트에서는 this.$emit('update-Input',this.inputData); 와같이 선언
부모 컴포넌트에서는 <TestComponents @update-Input="updateInput" /> 와 같이 선언

@update-Input로 받을 함수를 설정하면 해당 함수가 호출되어 이벤트나 데이터를 받을 수 있다.

----------------------------------------부모 컴포넌트 ----------------------------------------
<template>
  <div id="app">    
    <TestComponents @update-Input="updateInput" />    
    <p></p>
  </div>
</template>

<script>
import TestComponents from '@/components/TestComponents.vue'
export default {
  name: 'App',
  components: {        
    TestComponents
  },
  methods:{
    updateInput(inputData){
        console.log('root inputData='+inputData);            
    },    
  }
}
</script>


----------------------------------자식 컴포넌트 TestCompoents -------------------------------
<template>
  <div>
      <input type="text" v-model="inputData" @input="updateInput">
      <span>{{inputData}}</span>
  </div>
</template>

<script>
export default {
    data(){
        return{
            inputData:''
        }
    },
    methods:{
        updateInput(){
            console.log(this.inputData);
            this.$emit('update-Input',this.inputData);
        }
    }
}
</script>

slot (컴포넌트의 template slot 태그를 넣어 부모 컴포넌트로 다른 태그나 내용을 넣을 수 있다)

자식 컴포넌트의 template 태그의 slot 태그를 만들면 부모 컴포넌트에서 선언된 자식컴포넌트 태그 안에 html 코드나 내용을 입력하면 자식 컴포넌트의 slot태그 안에 추가 된다.

  1. 부모 컴포넌트에서 자식 컴포넌트 태그 안에 template 태그를 만들고 해당 속성에 v-slot이라는 이름을 적으면
    자식 컴포넌트 slot에 name이라는 속에 해당하는 slot의 태그안에 html 코드나 내용이 추가된다.
  2. 자식 컴포넌트의 slot에서 bind할 속성을 추가하면 해당 속성값을 부모 컴포넌트에서 slotValue로 값을 가져와 사용후 다시 자식 컴포넌트로 값을 전달 할 수 있다.
    <template #slotC="slotValue">slotC {{slotValue.testValue}}
-------------------------------부모 컴포넌트 ------------------------------
<template>
  <div id="app">    
    <TestComponents>
      <template v-slot:slotB>slotB</template>            
      <template v-slot:default>slot default</template> 
      <template #slotA>SlotA</template> <!-- v-slot:를 #:으로 줄일수 있음-->

      <!--자식 컴포넌트의 데이터를 slot 속성인 slotValue 에 넣어 부모 slot을 설정하는 곳에서 전달 받은 데이터 사용 가능 -->
      <template #slotC="slotValue">slotC {{slotValue.testValue}}</template> 
    </TestComponents>
    <p></p>
  </div>
</template>

----------------------------------자식 컴포넌트 TestCompoents -------------------------------
<script>
import TestComponents from '@/components/TestComponents.vue'
export default {
  name: 'App',
  components: {        
    TestComponents
  },  
}
</script>

<template>
  <div>
      <p>1</p>
      <slot name="slotA"></slot>
      <p>2</p>
      <slot></slot>
      <p>3</p>
      <slot name="slotB"></slot>
      <p>4</p>
    <!--자식 컴포넌트에서 사용하는 값을 부모 컴포넌트에서 받아서 다시 slot 안에 넣어준다 -->
      <slot name="slotC" v-bind:testValue="name"></slot> 
  </div>
</template>

0개의 댓글