- Vue
- 자바스크립트의 확장 프레임워크
- {{}} 문법을 사용해 실시간 데이터를 출력한다.
- 모델의 값이 변경되면 바로 반영된다.
- Vue.js 객체 선언 구조
1. Vue 객체 생성 후 Object를 return 함
new Vue({});
2. 반환 오브젝트 key 값은 vue에서 지정한 key 값을 사용한다.
- el 모델(데이터, key값) : vue모델을 사용할 부모 태그 영역을 지정함
- data 모델(데이터, key값) : 모델(데이터)들의 초기값을 설정(init)
- methods 모델(데이터, key값) : 함수(오브젝트)를 정의하는 모델
- computed 모델(데이터, key값) : 정의한 함수 내부 종속된 모델이 변경되면 다시 호출한다.
- component 모델(데이터, key값) : 태그 이름을 정의하고 html이 해석될 때 지정한 템플릿으로 변경한다.(jsp의 include와 동일)
- created:function(){} 모델 : 해당 페이지가 처음 실행되었을 때 한번만 실행되도록 하는 모델new Vue({ // 모델을 사용할 태그의 id가 app인 태그를 부모 태그로 설정 el:"#app", // 모델 정의 data:{ fortune:"동쪽으로 가면 귀인을 만나요!", myName:"김구라", msg:"", nums:[10, 20, 30] }, // 모델 컨트롤 methods:{ clicked:function(){ //alert("오잉?"); this.fortune="오후에도 vue 를 배우게 될거에요"; }, clicked2:function(){ //this.myName="에이콘"; this.nums=["김구라", "해골", "원숭이"]; } } });
- 태그 속성
- v-model 속성 : input 태그에서 입력한 value를 해당 속성 값(변수)에 자동 저장함
<input type="text" v-model="msg"/> <p>{{msg}}</p>
- v-on:click 속성 : 태그에 이벤트를 발생시키기 위한 속성(vue 객체의 methods 호출)
<button v-on:click="clicked">눌러보셈</button> <button v-on:click="clicked2">이름 바꾸기</button>
- v-on:submit.prevent 속성 : form에서 제출이되었을 때 .prevent로 제출을 막을 수 있다.
<form action="test.jsp" v-on:submit.prevent="onSubmit2"> <input type="text"> <button type="submit">전송</button> </form>
- v-for 속성 : for문을 설정하여 나오는 값을 {{}}문에 넣어 출력함
<!-- nums = [10, 20, 30] --> <ul> <li v-for="item in nums">{{item}}</li> </ul>
- v-text 속성 : 해당 요소의 innerText를 설정함
<input type="text" v-model="msg" > <p>{{msg}}</p> <p v-text="msg"></p>
- v-bind:class 속성 (오브젝트) : 해당 요소의 클래스를 추가하거나 삭제할 수 있다.(v-model을 사용해서 처리)
<button class="btn" v-bind:class="{'btn-primary':isPrimary, 'btn-lg':isLg}">Vue 버튼</button> <br> <label> 파란색 버튼 <input type="checkbox" v-model="isPrimary"> </label> <label> 큰 버튼 <input type="checkbox" v-model="isLg"> </label>
- v-bind:class 속성 (함수) : 해당 속성 값으로 computed 모델 함수를 지정하여 헨들링한다.
<button class="btn" v-bind:class="classObject">Vue 버튼</button> computed:{ classObject:function(){ return {'btn-primary':this.isPrimary, 'btn-lg':this.isLg}; } }
- v-bind:class 속성 (Array) : 해당 속성 값으로 Array를 지정하여 헨들링한다.
<button class="btn" v-bind:class="[ isPrimary ? 'btn-primary' : '', isLg ? 'btn-lg' : '']"> Vue 버튼 </button>
- v-bind:style 속성 : 해당 요소의 속성을 추가할 수 있다.
<p v-bind:style="{color:fontColor, fontSize: fontSize+'px'}"></p>
- v-if 속성 : 해당 요소를 제거하거나 생성할 수 있다.
<div class="box" v-if="true">aa</div>
- v-show 속성 : 해당 요소를 숨기거나 나타나게 할 수 있다.
<div class="box" v-show="true">aa</div>
- v-for속성 : for(a in arrays) 형식의 for문
<!-- array를 바로 넣었을 때 --> <li v-for="item in [10,20,30]">{{item}}</li> <!-- array 변수를 넣었을 때 --> <li v-for="item in nums">{{item}}</li> <!-- value와 index를 추출 --> <li v-for="(item, index) in nums">{{item}} {{index}}</li> <!-- object in array를 넣었을 때 --> <li v-for="item in members"> 이름 : {{item.name}} 주소 : {{item.addr}} </li>
- component : html을 클라이언트 사이드에서 불러올 수 있다.
↪ components 모델의 value 이름 == 개발자 정의 태그 이름
↪ v-bind의 속성값 == data 모델의 value 키 값
↪ v-bind:??? 값 == components의 props 내에 있는 array 요소<div id="app"> <my-component></my-component> <my-component></my-component> <my-component></my-component> <input type="text" v-model="msg"/> <your-component v-bind:greet="'안녕하세요!'"></your-component> <your-component v-bind:greet="msg"></your-component> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> let app=new Vue({ el:"#app", data:{ msg:"" }, components:{ "my-component":{ template:"<div class='box'> box </div>" }, "your-component":{ template:"<div class='box'>{{greet}}</div>", props:["greet"] } } }); </script>
- 최상단 부모 컴포넌트 가용 형식
// 1. 오브젝트 형식의 data 모델 let app=new Vue({ el:"#app", data:{ greet:"안녕하세요!" } }); // 2. function의 오브젝트 반환 형식 let app2=new Vue({ el:"#app2", data:function(){ return { greet:"안녕하세요!" }; } }); // 3. 함수 형식의 data 모델 let app3=new Vue({ el:"#app3", data(){ return { greet:"안녕하세요!" }; } });
- 자식 컴포넌트 가용 형식
// 자식 컴포넌트의 함수 형식 data 모델 Vue.component("my-component", { template:"<div>{{msg}}</div>", data(){ return { msg:"div 입니다." }; } });
- components 예제
<div class="container" id="app"> <h1>component 예제</h1> <div class="row"> <figure-component v-for="(item, index) in imageList" v-bind:imageinfo="item" v-bind:key="index"></figure-component> <!-- key는 for문의 각 요소의 식별자를 두기 위함 (생략 가능) --> </div> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> Vue.component("figure-component",{ template:` <div class="col"> <figure class="figure"> <img v-bind:src="imageinfo.src" class="figure-img img-fluid rounded"> <figcaption class="figure-caption">{{imageinfo.caption}}</figcaption> </figure> </div> `, props:["imageinfo"] }); let app=new Vue({ el:"#app", data(){ return { imageList:[ {src:"images/image1.png", caption:"어쩌구... 저쩌구..."}, {src:"images/image2.png", caption:"어쩌구... 저쩌구..."}, {src:"images/image3.png", caption:"어쩌구... 저쩌구..."}, {src:"images/image4.png", caption:"어쩌구... 저쩌구..."} ] }; } }); </script>
- img v-bind:src 속성 : img 요소의 src 속성에는 {{}} 문법을 사용할 수 없어 v-bind:src 속성을 사용하여 image 경로를 지정할 수 있다.
<!- 이미지 출력 불가능 --> <img src="{{path}}"></img> <!- 이미지 출력 가능 --> <img v-bind:src="path"></img>
- v-on:이벤트 이름 속성 : 개발자 지정 이벤트 정의로 이중 이벤트를 사용할 수 있다.
↪ 1. component 이름에 맞는 Vue 객체 component를 찾는다.
↪ 2. 매핑시킨 자식 컴포넌트에서 클릭 이벤트가 발생
↪ 3. 자식 컴포넌트 methods 모델에 정의한 callMom() 모델 함수가 실행된다.
↪ 4. this.$emit("개발자 지정 이벤트명", "전달할 파라미터")를 실행한다.
↪ 5. 개발자가 지정한 이벤트명(mom)이 발생하면 feed 모델 함수가 부모 Vue 객체에서 실행된다.
↪ 6. feed("전달받은 파라미터") 모델 함수가 실행되어 alert가 실행된다.<div id="app"> <my-component v-on:mom="feed"></my-component> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> Vue.component("my-component", { template:` <div> <button v-on:click="callMom">엄마!</button> </div> `, methods:{ callMom(){ // this.$emit("이벤트명", 전달할 data) this.$emit("mom", "배고파"); } } }); let app=new Vue({ el:"#app", methods:{ feed(data){ alert(data); } } }); </script>
- ref 속성 : id값으로 참조하는 방식과 동일하게 동작한다.
<div id="app"> <button v-on:click="clicked">눌러보셈</button> <input type="text" ref="one" > </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> let app=new Vue({ el:"#app", methods:{ clicked(){ // ref="one" 인 문서객체의 참조값 console.log(this.$refs.one); this.$refs.one.value="버튼을 눌렀네?"; } } }); </script>
- 참고 사항
- function(e) : 이벤트 객체를 가져옴
- e.target : 이벤트가 발생한 해당 문서 객체(DOM)을 참조함
- ref="aa" : id로 정의한 요소를 참조하는 것 대신 ref로 선언한 요소를 참조하여 사용한다.
- this.$ref.aa.focus : ref가 aa인 요소를 focus하는 methods 문법
- v-bind에서 프로퍼티를 지정할 때 이름이 긴 프로퍼티는 속성에서 케밥 케이스로 지정해야 한다.
- this.$set(this.모델명, 바꿀 요소의 인덱스, 바꿀 참조값)
- Ajax 통신
- 페이지 전환 없이 서버의 데이터를 통신하는 방식
- 미완성인 상태의 서버 데이터을 가져와 동적으로 DOM에 적용하는 방식
- Vue와 Ajax 통신 응용
- 클라이언트 side Rendering<div id="app"> <table> <thead> <tr> <th>번호</th> <th>작성자</th> <th>제목</th> </tr> </thead> <tbody> <tr v-for="tmp in list" v-bind:key="tmp.num"> <td>{{tmp.num}}</td> <td>{{tmp.writer}}</td> <td>{{tmp.title}}</td> </tr> </tbody> </table> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> new Vue({ el:"#app", data:{ list:[] }, created(){ // Vue 가 준비가 되었을때 (root component 가 준비 되었을때) 최조 한번 호출된다. console.log("created!"); //Vue 의 참조값을 self 에 담기 const self=this; fetch("/Step04_Final/cafe/json_list.jsp") .then(function(response){ return response.json(); }) .then(function(data){ console.log(data); //서버로 부터 받은 데이터를 list 에 대입하기 self.list=data; }); }, methods:{ } }); </script>
// JSON 형태로 html에 데이터를 주어 비동기 처리 방식으로 동작하게 된다. <%@page import="org.json.JSONWriter"%> <%@page import="test.cafe.dao.CafeDao"%> <%@page import="test.cafe.dto.CafeDto"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8"%> <% //글목록 얻어오기 List<CafeDto> list=CafeDao.getInstance().getList(); //JSON 문자열로 변환하기 String result=JSONWriter.valueToString(list); %> <%-- JSON 문자열을 그대로 client 에게 출력하기 --%> <%=result%>
- SPA
처음 로딩된 페이지에서 페이지 전환없이 해당 서비스가 제공하는 모든 content를 사용할 수 있는 어플리케이션
→ Vue.js 와 Ajax등의 여러 라이브러리를 사용해 SPA를 구현할 수 있다.