Vue.js, Vue3 - 템플릿 문법

김화영·2024년 7월 5일
0

Vue3

목록 보기
3/14
post-thumbnail

1. v-once

아래처럼 콘솔창에 msg를 직접 변경하면 변경된 문자 데이터로 재 렌더링되어 나타난다.

하지만, 태그 요소에 v-once를 사용하면 데이터 변경이 되지 않는다.
v-once : 기존에 렌더링 된 데이터를 한 번만 렌더링하고 변경시 반응은 하지 않음

    <div id="app">
        <div v-once> {{ msg }}</div> <!-- 문자 데이터 바인딩 -->
        <div> {{ msg }}</div>
        <div> {{ msg }}</div>
    </div>


2. v-html

일반적으로 script에서는 <br>이라는 html태그가 작동하지않는다.
예시로

            data() {
                return {
                    msg: 'Hello Vue! <br/> Good job~'
                };
            }, 

위처럼 script 코드를 작성하고 화면에서 확인해보면 아래처럼 출력된다.

이러한 원시적 html코드를 제대로 작동하게 하려면 v-html을 사용해야한다.

v-html은 문자 데이터 내의 html 코드를 해석하여 html요소로 작동시킨다.

    <div id="app">
        <div> {{ msg }}</div>
        <div v-html="msg"> {{ msg }}</div>
    </div>

3. {{ }} 보간(interpolation)

보간은 Vue 템플릿 문법에서 데이터 바인딩을 위해 사용된다. javascript에서 표현식이라고 사용되는 문법은 모두 보간에서 사용할 수 있다.

{{ num + 2 }}, {{ new Date }}, {{ Math.round(1.7) }} 등등


4. v-bind:class (:class)

vue의 템플릿 문법에서는 태그의 class도 관리할 수 있다.

    <style>
        .active { color: red; } // active라는 class의 글자 색은 red
    </style>

    <div id="app">
        <div v-bind:class="className"> {{ msg }}</div> 
      	<!-- div태그의 class는 vue에서 설정한 className으로 지정된다. -->
    </div>

    <script>
        const App = {
            data() {
                return {
                    msg: 'Hello Vue! <br/> Good job~',
                    className: 'normal'
                };
            }, 
            
        };

        const app = Vue.createApp(App).mount('#app')
        
    </script>

위와 같은 내용이라면 현재 id가 app인 div태그 안의 div태그의 class는 normal이다.

html 콘솔창에서 app.className = 'active'로 바꿔보면 어떨까?

위의 사진처럼 class가 active로 바뀌고 글자 색도 검정에서 빨간색으로 바뀌게 된다! 이는 동적 class도 동작이 가능하다는 것을 의미한다.


5. v-on:click

methods를 활용하여 클릭이벤트를 발생시켜보자. 이전에는 직접적으로 className을 변경했다면 click이벤트를 methods로 넣어 해당 메소드를 실행시키는 코드이다.

<style>
        .active { color: red;}
    </style>

    <div id="app">
        <div v-bind:class="className"> {{ msg }}</div>
        <button v-on:click="changeClassName()">changed btn</button>
    </div>

    <script>
        const App = {
            data() {
                return {
                    msg: 'Hello Vue!',
                    className: 'normal'
                };
            },
            mounted(){
                console.log(this.className)
            },
            methods: {
                changeClassName () {
                    this.className = 'active';
                    console.log(this.className)
                }
            }
        }

        const app = Vue.createApp(App).mount('#app')

    </script>

mounted 훅을 통해 버튼을 누르기 전 DOM에 렌더링 된 msg의 클래스를 확인하기로 했다.

위의 이미지처럼 class가 normal인 것을 확인 할 수 있다.

버튼을 누르게 되면 아래의 이미지처럼 변경된다.

class가 active로 변경 된 것을 볼 수 있고, 메소드가 정상 작동하여 콘솔에 표기되는 것을 확인 할 수 있다.

v-on@로 생략 할 수 있다. v-bind:로 생략되는 것 처럼!
v-on:click -> @click

profile
백엔드 개발자 주주주니어

0개의 댓글