Vue란?
front 앱의 기본 뼈대와 api를 제공하는 Java Script 프레임 워크이다.
컴포넌트 베이스 개발이다. 컴포넌트는 <template>(화면 ui 구성) , data, 메서드로 구성된다.
보다 동적이고 상호 호환적인 웹 애플리케이션을 개발하기 위해 사용된다.
사용방법
1. CDN 코드로 사용해서 빠르게 호출
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
2. 다운로드 후 설치
Node.js 설치 -> Vue 설치 .. 등의 과정을 거쳐 설치하여 사용한다. CDN 코드로 호출하는 것보다 더 많은 기능을 사용할 수 있다.
1. HTML 페이지 생성
2. div 생성
div 로 id 를 하나 부여하고, 해당영역을 Vue Application으로 할당해야한다.
3. Vue 어플리케이션 생성자
생성자를 선언하여 뷰 앱을 생성한다. 변수를 만들고 값을 할당하여 템플릿 내에서 출력하고 싶은 값을 출력한다.
app.mount('#app')은 생성한 app 객체를 템플릿에 붙인다. (생성한 app 객체를 아이디가 app인 곳에 넣는다는 의미)
<div id="app"></div> // @@얘랑
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const app = Vue.createApp({ //@@위에서 생성한 vue 어플리케이션 얘를 아래 mount를 이용해 위 div app이랑 연결
data() { //data가 템플릿 안에서
return {
message: "Hello World!"
}
}
})
app.mount('#app') //@@얘가 연결됨.
</script>
vue 변수 출력 표기법
div 내에서 출력한다.
<div id="app"> {{ message }} </div>
//{{ -> VUE 변수를 출력할때 사용하는 표기법
Directive (지시자)
v-bind | 태그 속성을 Vue 데이터 변수에 연결 | Connects an attribute in an HTML tag to a data variable inside the Vue instance. |
v-if | if 문 | Creates HTML tags depending on a condition. Directives v-else-if and v-else are used together with the v-if directive. |
v-show | 조건에 따라 HTML요소 표시 | Specifies if an HTML element should be visible or not depending on a condition. |
v-for | 루프, 목록 뿌릴때 (반복문) | Creates a list of tags based on an array in the Vue instance using a for-loop. |
v-on | 이벤트 핸들러 연결 | Connects an event on an HTML tag to a JavaScript expression or a Vue instance method. We can also define more specifically how our page should react to a certain event by using event-modifiers. |
v-model | 입력 요소와 Vue 인스턴스 바인딩 | Used in HTML forms with tags like <form>, <input> and <button>. Creates a two way binding between an input element and a Vue instance data property. |
v-bind
HTML태그의 속성을 Vue 인스턴스 내부의 데이터 변수에 연결하는데 사용된다. 즉, 특정한 값을 바인딩할때 사용한다. v-bind 를 사용하면 동적으로 속성 값을 설정할 수 있다.
<div v-bind:[HTML 태그 속성]="[값]"></div>
<img v-bind:src="url"> //바로 지정하는게 아니라 v-bind로 결합하겠다.
<div v-bind:title="msg">Hover over me </div>
바인딩하려는 속성 앞에 v-bind: 또는 ':'를 붙여 사용한다. v-bind는 생략하여 사용하기도 한다. Vue 인스턴스의 데이터가 변경되면 자동으로 업데이트되는 특징이 있어, 실시간 상호작용이 가능하다.
값을 소속을 시킬거냐 아니냐 true/false에 넣음
<div v-bind:class="{ myClass: true }">
The class is set conditionally to change the background color
</div>
v-bind 키워드 자주 생략하고 사용
<div :class="{ impClass: isImportant }">
The class is set conditionally to change the background color
</div>
* v-bind와 HTML 태그 속성 사이에 띄어쓰기는 사용하지 않아야한다.
<!-- 뷰 앱이 렌더링할 템플릿 생성 -->
<div id="app">
<h2 v-bind:style='{color:c1}'>{{text1}}</h2>
<h3 :style='{color:c2}'>{{text2}}</h3>
</div>
<script>
const app = Vue.createApp({
data() {
return {
c1:'orange',
c2:'yellow',
text1:'hello orange',
text2:'hello yellow'
}
}
})
app.mount('#app');
</script>
v-if
v-if 디렉티브를 사용하면 조건문을 적용하여 해당 조건이 참일 때에만 태그가 동작하도록 할 수 있다. Vue 인스턴스의 데이터에 기반하여 조건을 판단한다. 즉, <div v-if="[값이 true]">일때만 동작한다.
* &&와 ||(Oror) 전부 사용이 가능하다.
<div id="app"> //해당되는 조건이 실행됨
<p v-if="typewritersInStock"> //typewritersInstock이 true일 때 실행
in stock
</p>
<p v-else>//typewritersInstock이 false일 때 실행
not in stock
</p>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
typewritersInStock: false
}
}
})
app.mount('#app')
</script>
<body>
v-if. 조건문 (조건이 맞는지 아닌지에 따라 랜더링 )
<div id="app">
<h3 v-if='type==2'>판매자</h3>
<!-- <h3 v-else-if='type==1'>구매자</h3> -->
<h3 v-else>구매자</h3> <!-- 타입이 2일때만 판매자, 나머지 다 구매자 -->
</div>
<script>
const app = Vue.createApp({
data(){
return{
type:2
}
}
})
app.mount('#app');
</script>
v-show
조건에 따라 HTML 요소를 보이게 하거나 숨기는 기능을 제공한다. <script>에서 isVisible = true 이면 아래의 div 가 보일 것이고, false이면 보이지 않을 것이다. 조건에 따라 요소를 토글할 때 사용된다.
*v-show 디렉티브는 단순히 화면에 보이거나 숨기는 역할을 수행하므로, 숨겨진 요소에 대한 사용자의 입력/이벤트 처리가 가능하다.
<div v-show="isVisible">This is a visible element</div>
화면의 해당 영역을 렌더링 할거냐 말거냐
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <!-- 라이브러리 복사 -->
</head>
<body>
v-show: 화면에 보이게/안보이게 설정 디렉터
<div id="app">
<h3 v-show="vs" style="background-color:blue;width:100px;height:100px"></h3>
</div>
<script>
const app = Vue.createApp({
data(){
return{
vs:false
}
}
})
app.mount('#app');
</script>
</body>
</html>
v-for
자바의 For 문, 자바 스크립트의 <c:forEach> 태그와 동일하게 생각하면된다. 배열이나 객체를 기반으로 HTML 요소를 반복적으로 생성하는데 사용된다.
1.
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
위의 코드는 v-for 디렉티브는 items라는 배열과 연결되어있다. items 배열의 각 항목은 item 이라는 변수에 할당되어 반복문을 수행하고, 각 항목의 name 속성을 출력한다. :key 속성은 Vue.js가 각 요소를 식별하기 위해 사용되는 고유한 식별자이다.
자바스크립트의 <c:forEach var="item" items="items"> 와 동일하다.
2.
<div v-for="(value, key) in object">{{ key }}: {{ value }}</div>
객체를 순회하는 경우에도 사용할 수 있다. v-for 디렉티브는 object 라는 객체와 연결되어있다. object 객체의 각 속성은 value 와 key라는 변수에 할당되어 반복문을 수행하며, 각 속성의 키와 값을 출력한다.
key: 객체의 각 속성의 키가 key 변수에 할당되고, value: 객체의 각 속성의 값이 value 변수에 할당된다.
data() {
return {
object: {
name: 'John',
age: 25,
email: 'john@example.com'
}
};
}
<div>name: John</div>
<div>age: 25</div>
<div>email: john@example.com</div>
3.
<div v-for="(item, index) in items">{{ index }}: {{ item }}</div>
items 배열의 각 항목을 item이라는 변수에 할당하고, 추가로 해당 항목의 인덱스를 'index'라는 변수에 할당하여 반복문을 수행한다. 인덱스는 0부터 배열의 요소 순서를 나타낸다.
<div id="app">
<div v-for="(x, index) in Foods">
{{index}}: "{{x}}" <br>
</div>
</div>
<script>
const app = Vue.createApp({
data(){
return{
Foods:[
'Burrito',
"taco",
"Salad",
"Cake"
]
}
},
});
app.mount('#app');
</script>