상세 컨텐츠

본문 제목

Vue.js v-html 사용하여 style 적용하는 방법

기술이 된 상상

by Indigo_Pure 2023. 10. 27. 08:07

본문

728x90
반응형
Vue.js를 이용 중인데 json 데이터에 있는 텍스트를 그대로 불러와서 사용하고 있습니다.
텍스트에 줄바꿈이나 간격 등의 포맷을 적용하고 싶어요.

 

실행 환경

Vue.js version 3.3.4
Node.js version 16.20.0
MacOS Vertura

 

 프로젝트 구성(Optional)

Vue.js 프로젝트 설치

 

기본적으로 Vue.js 문서를 통해 구성된 프로젝트 구조를 예시로 듭니다. 

Vue.js 프로젝트가 이미 구성되었다면 skip 해도 무관하며 프로젝트를 구성하여 학습하고 싶다면

아래 링크의 Vue.js 프로젝트를 구성하는 방법을 참고하여 구성하세요.

 

Quick Start | Vue.js

VueConf Toronto - Join the premier Vue.js conference | 9-10 Nov 2023 - Toronto, CanadaView Schedule Use code VUEJS to get 15% off

vuejs.org

 

위 문서를 참고하여 간략하게 정리를 한다면 아래와 같습니다.

원하는 폴더로 이동 후 npm 명령어를 통해 Vue.js를 활용한 프로젝트를 생성합니다.

// Vue.js 프로젝트 구성 명령어
npm create vue@latest

// 프로젝트 설정
✔ Project name: … <your-project-name>
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit testing? … No / Yes
✔ Add an End-to-End Testing Solution? … No / Cypress / Playwright
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes

Scaffolding project in ./<your-project-name>...
Done.

 

 

기본 데이터 세팅

Vuejs에서 데이터를 넣어주고 있는데 아래 예제에서는 import 한 json 파일의 key 값에 할당된 value를 나타냅니다.

(프로젝트를 새로 생성하신 경우라면 해당 파일에 아래 코드를 복사/붙여넣기를 하셔도 됩니다.

// App.vue
<script setup>
import data from "./data.json";
</script>

<template>
  <header>
    <img
      alt="Vue logo"
      class="logo"
      src="@/assets/logo.svg"
      width="125"
      height="125"
    />
    <div class="wrapper">
      <div>{{ data.content }}</div>
    </div>
  </header>
</template>

 

App.js 와 동일 위치에 data.json 파일을 생성해줍니다.

// data.json
{
  "content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
}

 

실행 화면을 보면 아래와 같이 글자들이 표기됩니다.

JSON 데이터 string이 입력된 화면

JSON 데이터 파일의 글자에 스타일 넣기

JSON 안에 있는 텍스트를 불러와서 보여주었는데, 해당 내용이 그럴싸하게 보이도록 이것저것 css 스타일을 적용해보고 싶습니다.

그렇다면 string인 데이터가 아니라 DOM 구조로 바꿔주기만 하면 됩니다.

 

String 데이터를 DOM 구조로 바꾸자

// DOM 구조로 바꾸기 위해 HTML 요소를 추가
// data.json
{
  "content": "<span class='key-point'>Lorem Ipsum</span> is simply dummy text of the printing and typesetting industry.<br /><span class='key-point'>Lorem Ipsum</span> has been the <strong>industry's standard dummy text</strong> ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.<br /> It has survived not only five centuries, but also the leap into <span class='key-point'>electronic typesetting</span>, remaining essentially unchanged.<br /> It was popularised in the 1960s with the release of Letraset sheets containing <span class='key-point'>Lorem Ipsum</span> passages,<br /> and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
}

 

string으로만 이루어져있던 데이터에 추가하고 싶은 DOM 요소들을 추가해줍니다. br, strong, span(class를 추가해주기 위한 요소)...

class 속성을 통해 특정 style을 지정하고 싶다면 css를 추가해줍니다.

// main.css 마지막 줄에 추가
// main.css
.key-point {
  font-size: 15px;
  line-height: 1.5;
  color: gold;
}

 

데이터를 바꾸고 난 뒤에 실행 화면을 봅니다.

DOM 구조의 JSON 데이터

DOM 요소 역시 String으로 입력되었습니다.

 

 

String의 DOM 구조를 표현하기 위해 사용하는 v-html 속성

Vue.js에서 String으로 적용되는 DOM 요소를 표현하기 위해서는 v-html 속성을 이용합니다.

App.js 파일을 보면 div요소의 하위 속성으로 들어가 있던 데이터를 v-html 속성에 할당해 줍니다.

// App.vue
<script setup>
import data from "./data.json";
</script>

<template>
  <header>
    <img
      alt="Vue logo"
      class="logo"
      src="@/assets/logo.svg"
      width="125"
      height="125"
    />
    <div class="wrapper">
      <div v-html="data.content"></div>
    </div>
  </header>
</template>

 

실행 화면을 봅니다.

span 요소에 class 속성으로 정의한 key-point 스타일이 잘 적용되었습니다. 

DOM구조의 스타일이 적용된 JSON데이터

728x90
반응형

관련글 더보기