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>
<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를 선언한 태그에서사용하는 데이터는 값을 변경해도 처음에 한번 설정 된 값을 유지한다.
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>
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>
// 단일 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>
<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를 사용하여 연산이 오래걸리는 데이터에 대해서 캐싱 작업을 할수 있다
한번 연산 후 해당 연산을 하지 않고 자동으로 변수만 반환하여 성능을 향상할 수 다.
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>
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>
<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를 추가하여 현재추가한 태그를 반복적으로 추가 할 수 있다.
<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>
사용할 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>
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>
자식 컴포넌트인 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>
자식 컴포넌트의 template 태그의 slot 태그를 만들면 부모 컴포넌트에서 선언된 자식컴포넌트 태그 안에 html 코드나 내용을 입력하면 자식 컴포넌트의 slot태그 안에 추가 된다.
-------------------------------부모 컴포넌트 ------------------------------ <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>