본문 바로가기

Frontend/Vue3

[Vue3] 템플릿 문법

728x90
반응형

1. Text Interpolation

- 이중 중괄호 구문(콧수염 구문)을 사용한다.

- v-once directive를 사용하면 렌더링 이후 값이 변경되어도 처음 렌더링 할 때의 값을 유지한다.

<body>
    <div id="app">
      <p>Message: {{ msg }}</p>
      <p v-once>once : {{ msg }}</p>
      <button @click="change()">msg 변경</button>
    </div>

    <script>
      const { createApp, ref } = Vue

      const app = createApp({
        setup() {
          const msg = ref("Hello!!!");

          const change = () => {
            msg.value = "Bye!!";
          };
 
          return {
            msg, change
          }
        },
      })

      app.mount("#app")
    </script>
  </body>

 

버튼 누르기 전

 

버튼 누른 후

2. Raw HTML

- 콧수염 구문은 데이터를 일반 데이터로 해석하기 때문에 실제 HTML을 출력하려면 v-html을 사용해야 한다.

<body>
    <div id="app">
      <div>{{ rawHtml }}</div>
      <div v-text="rawHtml"></div>
      <div v-html="rawHtml"></div>
    </div>

    <script>
      const { createApp, ref } = Vue

      const app = createApp({
        setup() {
          const rawHtml = ref('<span style="color:red">This should be red.</span>')
 
          return {
            rawHtml,
          }
        },
      })

      app.mount("#app")
    </script>
  </body>

3. Attribute Bindings

- 콧수염 구문은 HTML 속성 내에서 사용할 수 없다.

- v-bind directive를 사용하여 데이터를 HTML 태그의 속성 값과 동기화 되도록 한다.

- 바인딩 값이 null이나 undefined인 경우 렌더링 요소에서 제거된다.

<body>
    <div id="app">
      <div v-bind:class="dynamicId">안녕하세요</div>
    </div>

    <script>
      const { createApp, ref } = Vue

      const app = createApp({
        setup() {
          const dynamicId = ref("my-id")
          // const dynamicId = ref(null);

          return {
            dynamicId,
          }
        },
      })

      app.mount("#app")
    </script>
  </body>

4. Javascript Expressions

- 콧수염 구문 내부/directive 속성 값에서 Javascript 표현식을 사용할 수 있다.

<body>
    <div id="app">
      {{ number + 1 }} <br />
      {{ seen ? 'YES' : 'NO' }}<br />
      {{ msg.split('').reverse().join('') }}<br />
      <div :id="`list-${id}`"></div>
    </div>

    <script>
      const { createApp, ref } = Vue

      const app = createApp({
        setup() {
          const msg = ref("Hello SSAFY!!!")
          const seen = ref(false)
          const number = ref(10)
          const id = ref("div")

          return {
            msg,
            seen,
            number,
            id,
          }
        },
      })

      app.mount("#app")
    </script>
  </body>

주의 사항

- 각 바인딩에는 하나의 단일 표현식만 포함될 수 있다.

- 표현식이 아닌 선언식인 경우 작동하지 않는다.

- 흐름제어는 작동하지 않는다. 삼항 표현식을 사용해야 한다.

 

728x90
반응형