<p>Message : {{ msg }}</p>
<div v-html="rawHtml"></div>
const rawHtml = ref('<span style="color:red">This should be red.</span>')
<div v-bind="dynamicId"></div>
<script>
const dynamicId = ref("my-id");
</script>
<script>
const dynamicId = ref("my-id");
</script>
<div id="my-id"></div>
{{ number + 1 }} {{ok ? 'YES':'NO'}} {{ message.split('').reverse().join('') }}
<div :id="`list${id}`"></div>
각 바인딩에는 하나의 단일 표현식만 포함될 수 있음
작동하지 않는 경우
<!-- 표현식이 아닌 선언식 -->
{{ const number = 1 }}
<!-- 제어문은 삼항 표현식을 사용해야 함 -->
{{ if(ok) {return message} }}
Directive의 속성 값은 단일 JavaScript 표현식이어야 함 (v-for, v-on 제외)
표현식 값이 변경될 때 DOM에 반응적으로 업데이트를 적용
<p v-if="seen">Hi There</p>
일부 directive는 directive 뒤에 콜론(":")으로 표시되는 인자를 사용할 수 있음
아래 예신는 href는 HTML <a> 요소의 href 속성 값을 myUrl 값에 바인딩 하도록 하는 v-bind의 인자
<a v-bind:href="myUrl">Link</a>
아래 예시의 click은 이벤트 수신할 이벤트 이름을 작성하는 v-on의 인자
<button v-on:click="doSomething">button</button>
<form @submit.prevent="onSubmit"></form>HTML의 속성 값을 Vue의 상태 속성 값과 동기화 되도록 함
<!-- v-bind.html -->
<img v-bind:src="imageSrc" alt="#" />
<a v-bind:href="myUrl">이동!!</a>
v-bind shorthand (약어)
<!-- v-bind의 생략 구문(약어) -->
<img :src="imageSrc" alt="#" />
<a :href="myUrl">이동!!</a>
Dynamic attribute name(동적 인자 이름)
<img :src="imageSrc" alt="#" />
<a :href="myUrl">이동!!</a>
<p :[dynamicattr]="dynamicValue">......</p>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const imageSrc = ref("https://picsum.photos/200");
const myUrl = ref("https://www.google.co.kr/");
const dynamicattr = ref("title");
const dynamicValue = ref("Hello Vue.js");
return {
imageSrc,
myUrl,
dynamicattr,
dynamicValue,
};
},
});
app.mount("#app");
</script>
객체를 :class에 전다랗여 클래스를 동적으로 전환할 수 있음
예시 1
<div :class="{ active: isActive }">Text</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const isActive = ref(false);
return {
isActive,
};
},
});
app.mount("#app");
</script>
객체에 더 많은 필드를 포함하여 여러 클래스를 전환할 수 있음
예시 2
<div class="static" :class="{ active: isActive, 'text-primary': hasInfo }">
Text
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const isActive = ref(false);
const hasInfo = ref(true);
return {
isActive,
hasInfo,
};
},
});
app.mount("#app");
</script>
반드시 inline 방식으로 작성하지 않아도 됨
반응형 변수를 활용해 객체를 한번에 작성하는 방법
<div class="static" :class="classObj">Text</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const isActive = ref(false);
const hasInfo = ref(true);
const classObj = ref({
active: isActive,
"text-primary": hasInfo,
});
return {
isActive,
hasInfo,
classObj,
};
},
});
app.mount("#app");
</script>
:class를 배열에 바인딩하여 클래스 목록을 적용할 수 있음
예시 1
<div :class="[activeClass, infoClass]">Text</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const activeClass = ref("active");
const infoClass = ref("text-primary");
return {
activeClass,
infoClass,
};
},
});
app.mount("#app");
</script>
배열 구문 내에서 객체 구문을 사용하는 경우
예시 2
<div :class="[{ active: isActive }, infoClass]">Text</div>
:style은 JavaScript 객체 값에 대한 바인딩을 지원(HTML style 속성에 해당)
예시 1
<div :style="{ color: activeColor, fontSize: fontSize + 'px'}">Text</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const activeColor = ref("crimson");
const fontSize = ref(50);
return {
activeColor,
fontSize,
styleObj,
styleObj2,
};
},
});
app.mount("#app");
</script>
실제 CSS에서 사용하는 것처럼 :style은 kebab-cased 키 문자열도 지원 (단, camelCase 작성을 권장)
예시 2
<div :style="{ color: activeColor, 'font-size': fontSize + 'px'}">Text</div>
반드시 inline 방식으로 작성하지 않아도 됨
반응형 변수를 활용해 객체를 한번에 작성하는 방법
<div :style="styleObj">Text</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const activeColor = ref("crimson");
const fontSize = ref(50);
const styleObj = ref({
color: activeColor,
fontSize: fontSize.value + "px",
});
return {
activeColor,
fontSize,
styleObj,
};
},
});
app.mount("#app");
</script>
여러 스타일 객체를 배열에 작성해서 :style을 바인딩 할 수 있음
작성한 객체는 병합되어 동일한 요소에 적용
<div :style="[styleObj, styleObj2]">Text</div>
<!-- <div style="color: blue; font-size: 50px; border: 1px solid black;">Text</div> -->
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue
const app = createApp({
setup() {
const activeColor = ref('crimson')
const fontSize = ref(50)
const styleObj = ref({
color: activeColor,
fontSize: fontSize.value + 'px'
})
const styleObj2 = ref({
color: 'blue',
border: '1px solid black'
})
return {
activeColor,
fontSize,
styleObj,
styleObj2
}
}
})
app.mount('#app')
</script>
v-on:event="handler"
Inline handlers는 주로 간단한 상황에 사용
<!-- event-handling.html -->
const count = ref(0)
<button @click="count++">Add 1</button>
<p>Count: {{ count }}</p>
Inline handlers로는 불가능한 대부분의 상황에서 사용
<button @click="myFunc">Hello</button>
<script>
const name = ref("Alice");
const myFunc = function (event) {
console.log(event);
console.log(event.currentTarget);
console.log(`Hello ${name.value}!`);
};
</script>
Method Handlers는 이를 트리거하는 기본 DOM Event 객체를 자동으로 수신
<script>
const myFunc = function(event){
console.log(event);
console.log(event.currentTarget);
console.log(`Hello ${name.value}
}
</script>
메서드 이름에 직접 바인딩하는 대신 Inline Handlers에서 메서드를 호출할 수도 있음
이렇게하면 기본 이벤트 대신 사용자 지정 인자를 전달할 수 있음
<button @click="greeting('hello')">Say hello</button>
<button>Say bye</button>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const count = ref(0);
const name = ref("Alice");
const myFunc = function (event) {
console.log(event);
console.log(event.currentTarget);
console.log(`Hello, ${name.value}`);
};
const greeting = function (message) {
console.log(message);
};
const warning = function (message, event) {
console.log(message);
console.log(event);
};
return {
count,
name,
myFunc,
greeting,
};
},
});
app.mount("#app");
</script>
Inline Handlers에서 원래 DOM 이벤트에 접근하기
$event 변수를 사용하여 메서드에 전달
<button @click="warning('경고입니다.', $event)">Submit</button>
<button @click="warning($event, '경고입니다.')">Submit</button>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const count = ref(0);
const name = ref("Alice");
const myFunc = function (event) {
console.log(event);
console.log(event.currentTarget);
console.log(`Hello, ${name.value}`);
};
const greeting = function (message) {
console.log(message);
};
const warning = function (message, event) {
console.log(message);
console.log(event);
};
return {
count,
name,
myFunc,
greeting,
warning,
};
},
});
app.mount("#app");
</script>
Vue는 v-on에 대한 Event Modifiers를 제공해 event.preventDefault()와 같은 구문을 메서드에서 작성하지 않도록 함
stop, prevent, self 등 다양한 modifiers를 제공
<form @submit.prevent="onSubmit">...</form>
<a @click.stop.prevent="onLink">...</a>
form을 처리할 때 사용자가 input에 입력하는 값을 실시간으로 JavaScript 상태에 동기화해야 하는 경우 (양방향 바인딩)
양방향 바인딩 방법
v-bind를 사용하여 input요소의 value 속성 값을 입력 값으로 사용
v-on을 사용하여 input 이벤트가 발생 할 대마다 input 요소의 value 값을 별도 반응형 변수에 저장하는 핸들러를 호출
<p>{{ inputText1 }}</p>
<input :value="inputText1" @input="onInput" />
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const inputText1 = ref("");
// input의 value 값을 계속해서 반응형 변수 inputText1에 할당을 하는 함수
const onInput = function (event) {
inputText1.value = event.currentTarget.value;
};
return {
inputText1,
onInput,
};
},
});
app.mount("#app");
</script>
form input 요소 또는 컴포넌트에서 양방향 바인딩을 만듦
v-model을 사용하여 사용자 입력 데이터와 반응형 변수를 실시간 동기화
<p>{{ inputText1 }}</p>
<input :value="inputText1" @input="onInput">
<p>{{ inputText2 }}</p>
<input v-model="inputText2">
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue
const app = createApp({
setup() {
const inputText1 = ref('')
const inputText2 = ref('')
// input의 value 값을 계속해서 반응형 변수 inputText1에 할당을 하는 함수
const onInput = function (event) {
inputText1.value = event.currentTarget.value
}
return {
inputText1,
inputText2,
onInput
}
}
})
app.mount('#app')
</script>
단일 체크 박스와 boolean 값 활용
<input type="checkbox" id="checkbox" v-model="checked" />
<label for="checkbox">{{ checked }}</label>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const checked = ref(false);
return {
checked,
};
},
});
app.mount("#app");
</script>
여러 체크박스와 배열 활용
<div>Checked names: {{ checkedNames }}</div>
<input type="checkbox" id="alice" value="Alice" v-model="checkedNames" />
<label for="alice">Alice</label>
<input type="checkbox" id="bella" value="Bella" v-model="checkedNames" />
<label for="bella">Bella</label>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const checked = ref(false);
const checkedNames = ref([]);
return {
checked,
checkedNames,
};
},
});
app.mount("#app");
</script>
select에서 v-model 표현식의 초기 값이 어떤 option과도 일치하지 않는 경우 select 요소는 선택되지 않는 상태로 렌더링 됨
<div>Selected: {{ selected }}</div>
<select v-model="selected">
<option disabled value="">Please select one</option>
<option>Alice</option>
<option>Bella</option>
<option>Cathy</option>
</select>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const checked = ref(false);
const checkedNames = ref([]);
const selected = ref("");
return {
checked,
checkedNames,
selected,
};
},
});
app.mount("#app");
</script>