devWonny 2021. 10. 9. 21:08

#1. Vue 란?

#2. Vue 시작하기

#3. 인스턴스와 컴포넌트

#4. Chart.js 라이브러리 추가

#5. 차트 추가하기

#6.

#1. Vue 란?

Vue.js는 웹 애플리케이션의 사용자 인터페이스를 만들기 위해 사용하는 오픈 소스 프로그레시브 자바스크립트 프레임워크이다. (위키백과)

Angular VS React VS Vue

Angular React Vue
Written TypeScript JavaScript JavaScript
Initial
Release
2016, Google. 2013, Facebook. 2014, Google Employee
Data
Binding
양방향 바인딩
(사용자 입력 등 UI가 업데이트 될 때 모델의 상태를 변경)
단방향 바인딩
(모델 먼저 업데이트한 다음, UI요소를 렌더링)
단방향 바인딩
(모델 먼저 업데이트한 다음, UI요소를 렌더링, v-model 속성값을 추가함으로써 양방향 바인딩으로 전환 가능)
Ideal for 빠른 컴파일
앱의 스케일이 클 때
높은 유연성
원하는 패키지만 추가해 사용
작은 라이브러리 용량
싱글 페이지 개발에 적합

Angular

<div> <h2>Hello {{message}}</h2> </div> import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: 'src/app/app.component.html' }) export class AppComponent { constructor() {} message: string = 'Angular'; })

React

<div id="greeting"></div> <script type="text/babel"> class Gretting extends Component { render() { return ( <p>Hello from React</p> ); } } ReactDom.render(<Greeting />, document.getElemnetById('greeting')); </script>

Vue

<div id="greeting">{{message}}</div> <script> class Vue({ el: '#greeting', data: { message: 'Hello from Vue' } } </script>

#2. Vue 시작하기

Vue 설치

https://cli.vuejs.org/guide/installation.html

1. Node.js 설치

2. node.js 및 npm 버전 확인

3. Vue 설치

(별도 설정없이 기본값으로 우선 설치하였음.)

# Node.js 설치 후 터미널에서 버전 확인 C:\Users\xeonmin> C:\Users\xeonmin>node --version v14.17.6 C:\Users\xeonmin>npm --version 6.14.15 C:\Users\xeonmin> # npm 명령어를 이용하여 Vue 설치 C:\Users\xeonmin>npm install -g @vue/cli (생략...) C:\Users\xeonmin> C:\Users\xeonmin>vue --version @vue/cli 4.5.13 C:\Users\xeonmin> C:\Users\xeonmin>

Vue 프로젝트 생성

https://cli.vuejs.org/guide/installation.html

1. Vue 프로젝트 생성

npm audit fix의 경우, npm의 취약점을 안내해주는 명령어

생성 직후 아래 이미지와 같이 README.md 에 방법이 안내되어 있다.

2. 라이브러리 install

(추가한 라이브러리가 따로 없으면 생략.)

3. 빌드 or 실행

# Vue 프로젝트 생성 D:\IdeaProjects>vue create dashboard Vue CLI v4.5.13 ✨ Creating project in D:\IdeaProjects\dashboard. ⚙️ Installing CLI plugins. This might take a while... [ ..............] \ fetchMetadata: sill resolveWithNewModule find- (생략...) found 34 vulnerabilities (16 moderate, 18 high) run `npm audit fix` to fix them, or `npm audit` for details ⚓ Running completion hooks... � Generating README.md... � Successfully created project dashboard. � Get started with the following commands: $ cd dashboard $ npm run serve # 설치 마지막에 안내된대로, 새로 생성한 프로젝트 내부로 이동하여($ cd dashboard), 프로젝트를 실행하자(npm run serve). D:\IdeaProjects>cd dashboard D:\IdeaProjects\dashboard> D:\IdeaProjects\dashboard>npm run serve > dashboard@0.1.0 serve D:\IdeaProjects\dashboard > vue-cli-service serve INFO Starting development server... 98% after emitting CopyPlugin DONE Compiled successfully in 2555ms 오후 5:25:14 App running at: - Local: http://localhost:8080/ - Network: http://10.60.1.41:8080/ Note that the development build is not optimized. To create a production build, run npm run build.

#3. 인스턴스와 컴포넌트

뷰 인스턴스

뷰 인스턴스는 뷰로 화면을 개발하기 위해 필수적으로 생성해야하는 기본 단위.

뷰 인스턴스의 옵션 속성으로는, data, el, template, component, 뷰 라이프사이클(beforeCreate, created, beforeMount,...) 등의 속성을 사용할 수 있다.

뷰 라이프사이클

인스턴스의 상태에 따라 호출할 수 있는 속성을 라이프사이클 이라고 한다.

존재하지 않는 이미지입니다.

# 라이프 사이클 적용 예시 <div id="app">{{message}}</div> <script> class Vue({ el: '#app', data: { message: 'Hello from Vue' }, beforeCreate: function() { console.log("beforeCreate") }, updated: function() { console.log("updated") } </script>

컴포넌트

Component란 조합하여 화면을 구성할 수 있는 블록(화면의 특정 영역)을 의미한다.

컴포넌트는 여러 인스턴스에서 공통적으로 사용할 수 있는 전역 컴포넌트와, 특정 인스턴스에서만 유효한 범위를 갖는 지역 컴포넌트로 나누어진다.

# 전역 컴포넌트 / 지역 컴포넌트 선언 ... <div class="chart"> <global></global> <local></local> </div> ... <script> // 전역 컴포넌트 등록 Vue.component('global', { template: '<div>전역 컴포넌트</div>' }); // 지역 컴포넌트 등록 var cmp = { template: '<div>지역 컴포넌트</div>' } Vue.component('global', { el: '#app', components: { 'local': cmp } }); </script>

#4. Chart.js 라이브러리 추가

차트 선택 기준

- 간단히 한페이지 정도에서만 쓸 사용하기 쉬운 라이브러리 필요

- Vue wrapper 존재 여부

cf. 10 Best Vue Chart Libraries

https://openbase.com/categories/js/best-vue-chart-libraries

cf. Vue.js 에서 사용할 차트 추천

https://jeongwooahn.medium.com/vue-js-%EC%97%90%EC%84%9C-%EC%82%AC%EC%9A%A9%ED%95%A0-%EC%B0%A8%ED%8A%B8-%EC%B6%94%EC%B2%9C-4390f704bc7b

Chart.js 설치

https://www.chartjs.org/

https://vue-chartjs.org/guide/#installation

$ npm install vue-chartjs chart.js

# chart.js와 vue-chartjs(chart.js의 Vue wraaper) 설치 D:\IdeaProjects\dashboard> D:\IdeaProjects\dashboard>npm install vue-chartjs chart.js npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) + chart.js@3.5.1 + vue-chartjs@3.5.1 added 4 packages from 38 contributors and audited 1338 packages in 16.279s 91 packages are looking for funding run `npm fund` for details found 34 vulnerabilities (16 moderate, 18 high) run `npm audit fix` to fix them, or `npm audit` for details D:\IdeaProjects\dashboard>

package.json 내 라이브러리들이 추가된 것을 확인할 수 있다.

(package.json 파일은 배포한 모듈 정보를 담고자 만들어졌지만, 노드로 작성하는 애플리케이션도 package.json 파일을 사용하여 관리)

# D:\IdeaProjects\dashboard\package.json ... "dependencies": { "chart.js": "^3.5.1", "core-js": "^3.6.5", "vue": "^3.0.0", "vue-chartjs": "^3.5.1" }, "devDependencies": { "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-service": "~4.5.0", "@vue/compiler-sfc": "^3.0.0", "babel-eslint": "^10.1.0", "eslint": "^6.7.2", "eslint-plugin-vue": "^7.0.0" }, ...

#5. 차트 추가하기

차트 컴포넌트 생성

# <script> import { Line } from "vue-chartjs"; export default { extends: Line, data: ()=> ({ chartdata: { labels: ["January", "February"], datasets: [ { label: "Data One", backgroundColor: "#f87979", data: [40, 20] } ] }, options: { responsive: true, maintainAspectRatio: false } }), mounted() { this.renderChart(this.chartdata, this.options); } }; </script>

컴포넌트 추가

# Chart.vue <template> <line-chart /> </template> <script> import LineChart from './LineChart.vue' export default { name: 'Chart', components: { LineChart } } </script> # Vue 추가 <template> <img alt="Vue logo" src="./assets/logo.png"> <HelloWorld msg="Welcome to Your Vue.js App"/> <Chart /> </template> <script> import HelloWorld from './components/HelloWorld.vue' import Chart from './components/Chart.vue' export default { name: 'App', components: { HelloWorld, Chart }, beforeCreate: function() { console.log("beforeCreate") } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>

[출처] Vue + Chart|작성자 merrylili