Vue.js
[Vue.js] 템플릿 문법
ahleum
2023. 1. 5. 12:56
v-once
<div v-once ></div>
데이터를 한 번만 랜더링 하고 데이터가 변경되더라도 화면을 갱신하지 않는다
v-html
<template>
<div>{{msg}}</div> // <div>hello!</div> 출력
<div v-html="msg"></div> // hello! 출력
</template>
<script>
export default {
name: "test",
data(){
return{
msg:'<div>hello!</div>'
}
}
};
</script>
만약 데이터 자체가 태그를 포함하고 있는 상태에서 {{ }} 이렇게 출력을 하게 되면
그대로 문자열로 출력을 하기 때문에 태그까지 문자열로 출력이 되는데 이럴 때 사용하는 게 v-html이다
v-bind
html 속성에 {{ }} 문법을 사용하여 값을 동적으로 바인딩 할때 필요한 방법
속성을 넣는 방법이라고 생각하면 편할듯
<template>
<div v-bind:class="msg">{{msg}}</div>
</template>
<script>
export default {
name: "test",
data(){
return{
msg:'active'
}
}
};
</script>
<style scoped>
.active{
color: red;
}
</style>
위처럼 작성하면 class는 active로 바뀌고 style이 적용돼서 출력이 된다
v-bind 약어
- v-bind를 생략해줄 수 있다
:class
:href
이런 식으로 사용해주면 된다.
v-on
onclick 등 이벤트핸들링을 진행할 수 있다.
작성은 아래처럼 진행하며
<div v-on:click='changeText' > {{ text }} </div>
위 태그 부분을 클릭하면 changeText 함수가 실행되며 또는 함수명을 적지 않고 바로 작성도 가능하다.
v-on:click='num++' 이런 식으로도 작성이 가능하다
v-on 약어
- v-on을 생략하고 :대신 @을넣어주면 된다
ex) @click=' '
만약 v-bind나 v-on 등 뒤에 data로 이용하여 넣어줄 때는 대괄호를 이용하여 넣어줄 수 있다.
<template>
<div :[attr]="msg">안녕</div>
<div @[event]="msg+'!!'">변화</div>
</template>
<script>
export default {
name: "test",
data(){
return{
msg:'active',
attr:'class',
event:'click'
}
}
};
</script>
만약 위 예시에서
<div :[attr]="msg">안녕</div>
msg 변수가 아닌 문자열로 넣고 싶을 때는
" " 안에 ' '을 넣고 그 안에 문자열로 작성해주면 된다.
<div :[attr]="'string'">안녕</div>