Vue.js 사용 방법

[설치 방법]

  • npm 사용

    1. npm install -g vue

    2. npm install -g @vue/cli (여기서 CLI는 command-line interface; 예전 version은 "vue-cli" 사용)

    3. npm install -g @vue/cli-initnp (vue init 하기 위해 필요한 package)

[실행]

- 기본 HTML sample

<html>

<head>

<meta charset="UTF-8" />

</head>

<body>

<div id="app">

{{ message }}

</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>

const myApp = new Vue({

el: '#app', // el(DOM element 의미): HTML에서 id="app"으로 접근 필요

data: {

message: 'Hello Vue!'

}

});

</script>

</body>

</html>


[기본 문법]

- 자세한 내용: https://kr.vuejs.org/v2/guide/

- Vue.js는 MVVM 개념으로 구성됨

    • 전통적인 MVC: view(사용자와 UI 담당) - controller(view와 model 연락 담당) - model(logic, 두뇌 역할)

    • 새로운 MVVM: view(viewmodel에 따라 변경됨) - viewmodel(view가 필요로 하는 data, action을 담고 있는 container object) - model(MVC model과 동일)

      • Viewmodel: view가 model에 event를 전달하도록 돕는 중계자

- {{ variable }} 안에서는 단일 변수 형태 처리만 가능함

- 내부 object에 접근

    • Data를 바꾸면 저절로 rendering이 일어남(매우 편리): reactive website

    • 위 예 경우: myApp.$data.message = 'Test Vue!';

    • $data 의미: myApp의 member인 data에 접근, data는 message란 key를 가진 객체임

[Directives]

- "v-" 접두사를 사용하면 directive로 작용(쉽게 단일 JavaScript 명령이라 생각)

    • Directive 명령에서 함수 호출은 "fun()"과 "fun" 모두 가능: 다시 말해 괄호 생략 가능

- Directive 안에 여러 명령어를 쓸 때는 , 로 구분함(;를 쓰면 error 발생)

- v-bind: 특정한 HTML 항목을 Vue instance property로 고정

<div id="app">

<span v-bind:title="message">

Hover your mouse over me for a few seconds to see my dynamically bound title!

</span>

</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>

const myApp = new Vue({

el: '#app',

data: {

message: 'You loaded this page on ' + new Date().toLocaleString()

}

});

</script>

    • 위 예 경우: span의 title 속성을 property인 message로 치환; message는 myApp.$data.message를 가리킴

    • v-bind를 생략해 :title로 써도 됨

    • div style을 수정하는 방법

<div id="barElement" :style="`width:100%;height:${chartHeight}px`"></div>

-. charHeight는 data() {...} 안에 써서 export default를 함

- v-if: if 구문 수행

<div id="app">

<span v-if="seen">Now you see me</span>

</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>

const myApp = new Vue({

el: '#app',

data: {

seen: true

}

})

</script>

    • 위 예 경우: seen이 true인 경우에만 해당 span을 표시

- v-for: for 구문 수행

    • v-bind:key가 필수적으로 추가되어야 함, 혹은 v-bind:key의 사용이 권장됨

= 필수 tag 종류: <a> <span> <li>

= 권장 tag 종류: 나머지 전부

<div id="app">

<ol>

<li v-for="todo in todos" :key="todo.text">

{{ todo.text }}

</li>

</ol>

</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>

const myApp = new Vue({

el: '#app',

data: {

todos: [

{ text: 'JavaScript' },

{ text: 'Vue' },

{ text: 'Nuxt' }

]

}

})

</script>

  • Table에서는 다음과 같이 처리

<tbody>

<template v-for="i in names.length">

<tr :key="i">

<td>{{ i }}</td> <td>{{ names[i-1] }}</td>

</tr>

</template>

</tbody>

  • Directive 안에 있는 for in은 JavaScript의 for in과 다르게 사용될 수 있음

-> JavaScript의 for in은 object의 key를 가져올 때 사용함

-> array에 for in을 사용하면 value가 아닌 index가 넘어옴: 예) let a = ['a', 'b', 'c']; for (n in a) console.log(n) // 0, 1, 2가 출력됨

-> Vue.js에서는 for in을 array에 대해서 쓰더라도 index가 아닌 value를 잘 얻을 수 있음

- v-on: on event 처리

    • v-on:click -> Click할 때 처리할 event 정의

= 간략화해서 @click으로 표기 가능

- v-model: input이나 form에 사용되는 만능 directive

    • v-model = v-bind와 v-on을 쓰는 two-way binding을 하나로 처리

    • 예시) <input type="text" v-model="inputText">: script의 data() 안에 inputText를 정의해서 입력값을 받을 수 있음

    • 위 코드는 <input v-bind:value="inputText" v-on:input="updateInput">로 나누어서 쓸 수 있음: 하지만 이 방식은 v-bind와 v-on을 써야 하는 불편함이 있음

[Component]

  • 기본 HTML element를 확장하여 재사용 가능한 형태로 캡슐화하는 방식

= Component는 HTML에서 tag처럼 작용함

  • 전역 component를 JS에 등록하는 방법

new Vue({

el: '#some-element',

// 옵션

});

Vue.component('my-component', {

// 옵션

});

  • 전역 component를 HTML에서 사용하는 방법

<div id="example">

<my-component></my-component>

</div>

  • 지역 component로 JS에 등록하는 방법

var Child = {

template: '<div>사용자 정의 컴포넌트 입니다!</div>'

};

new Vue({

// ...

components: {

// <my-component> 는 상위 템플릿에서만 사용할 수 있습니다.

'my-component': Child

}

});

[Template]

  • Template은 Vue instance의 data와 HTML tag를 연결하여 정의하는 재사용할 수 있는 HTML 틀

  • Template을 정의하는 다양한 방법

https://vuejsdevelopers.com/2017/03/24/vue-js-component-templates/

  • 특히 객체 지향에는 SFC(single file component)가 유리함

= 확장자는 *.vue

= SFC는 vue-loader로 compile됨

<template>

<div class="checkbox-wrapper" @click="check">

<div :class="{ checkbox: true, checked: checked }"></div>

<div class="title">{{ title }}</div>

</div>

</template>

<script>

export default {

data() {

return { checked: false, title: 'Check me' }

},

methods: {

check() { this.checked = !this.checked; }

}

};

</script>

[HTML5]

- 자세한 내용: https://www.w3schools.com/html/default.asp

- Structural elements

<header>: Used to contain the header content of a site.

<footer>: Contains the footer content of a site.

<nav>: Contains the navigation menu, or other navigation functionality for the page.

<article>: Contains a standalone piece of content that would make sense if syndicated as an RSS item, for example a news item.

<section>: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article.

<aside>: Defines a block of content that is related to the main content around it, but not central to the flow of it.

https://www.w3.org/wiki/HTML_structural_elements?utm_source=twitterfeed

- Emmet 사용 방법: https://emmet.io/

    • 자세한 문법 설명: https://docs.emmet.io/abbreviations/syntax/

    • Tag 쓰고 . 찍으면 class 표현(tag 쓰지 않고 . 찍으면 자동으로 div로 인식)

    • Tag 쓰고 # 쓰면 id 표현

    • > 쓰면 child 표현

    • + 쓰면 sibling 표현

    • ^ 쓰면 climb-up 표현

    • *숫자(예를 들면 *5) 쓰면 반복 생성

    • () 쓰면 grouping 표현

    • $과 *를 같이 쓰면, class나 id 이름에 line numbering 부여


[CSS 적용]

- Bulma framework 사용

- 기본 HTML sample

<!DOCTYPE html><html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Hello Bulma!</title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.2/css/bulma.min.css">

<script defer src="https://use.fontawesome.com/releases/v5.15.3/js/all.js"></script>

</head>

<body>

<section class="section">

<div class="block">

<h1 class="title"> Hello World </h1>

<p class="subtitle"> My first website with <strong>Bulma</strong>! </p>

</div>

</section>

</body>

</html>

-> <script defer></script>를 이용하면 script를 background에서 download함

-> Bulma가 제공하는 class 이름을 쓰고, 특성 변경(modifier)에는 "is-$variable" 혹은 "has-$variable" 사용

= is-small, is-large, is-white, is-light, is-primary, is-outlined 등 가능

= has-text-black, has-background-white 등 가능

= 단순 text라면 class="content"로 선언

  • 기본 개념

-> Code를 표현할 때: <code>a = 10;</code> 혹은 <code class="html">HTML</code>

-> 도움말(help): <p class="help is-success">help</p>

-> bd-$variable: 큰 의미 없고 Bulma document용이라는 comment

-> fa or fas: solid

-> fab: brands

-> far: regular

-> fal: light

  • 그림

-> 그림을 중앙에 정렬(figure tag 사용)

<figure class="image container is-128x128">

<img src="a.jpg" alt=""/>

</figure>

-> 그림을 중앙에 정렬(figure tag 미사용)

<div class="content has-text-centered"><img src="a.png"></div>

  • 정렬

-> 양쪽 정렬: <div class="content has-text-justified">...</div>


[Vue.js 참고 문헌]

(Basics)

- Progressive JavaScript Framework: Vue.js Org, Vue.js Org - 한국어

- Intro to Vue.js

- Vue.js: a (re)introduction

- 4 Essential ES2015 Features For Vue.js Development

- Extend a default layout or create custom layouts in your SPA application Vue.js

- Creating an animated sidebar component with Vue and Vuex

- Simple tab navigation with Vue.js and Bulma

- Async in Vue.js - Part 1

(Form/Data)

- Form Validation with Vue.js

- Anyway, this is how to use v-model with Vuex. Computed setter in action.

- Data Driven Vue.js

- Vuetify: Material Design based UI toolkits

- An introduction to dynamic list rendering in Vue.js

(Components)

- 11 Vue.js UI Component Libraries You Should Know In 2018

- Managing User Permissions in a VueJS App

- VueJs: Routing with vue-router

- Do we need Higher Order Components in Vue.js?

- How To Add the Infinite Scrolling Effect to a Vue.js App

(Firebase)

- Building a Progressive Quiz App with Vue, Vuex, and Firestore: Part 1

- Build a Quiz Game App with Vue, Vuex and Firebase[Part 1]

- Introduction to VueFire

- Build A Simple App with VueJS and Firebase—Part 1

(etc.)

- Build a shopping cart with Vue.js and Element UI (no Vuex)

- Simple communication between Vue.JS components using the EventBus

- Building a custom Google Map component with Vue.js

- Travis Horn: JavaScript, Web Development

- Vue Component for Dynamically Updating Human Readable Time

- Vue Storefront: headless and backend-agnostic eCommerce PWA written in Vue.js


[HTML5/CSS 참고 문헌]

- How to make your HTML responsive by adding a single line of CSS

- Learn CSS Grid in 5 Minutes

- Learn CSS Variables in 5 minutes

- Bulma: an open source CSS framework based on Flexbox

- Bulma CSS Framework Crash Course

- Simple tab navigation with Vue.js and Bulma

- Bulma preview

- A Guide to CSS Animation — Part 1