Vue JS - BASIC

Alpha, Orderly·2024년 1월 15일
0

VueJS

목록 보기
1/2

Vue JS

  • Multi page application 의 위젯으로서 사용될수 있다.
  • 혹은 Single page application 으로 전체 페이지를 담당하게 할수 있다.

Vue 사용하기

    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="app.js"></script>
  • CDN으로 부터 script 를 받아와 사용할수 있다.
  • 아래 app.js 에 사용자의 코드를 작성한다.

HTML 문서에 Vue 적용하기

Vue 가 적용될 부분 정하기

index.html

<section id="user-goal">
      <h2>My Course Goal</h2>
      <p></p>
</section>

app.js

Vue.createApp({
...
}).mount("#user-goal")
  • .mount("CSS 선택자") 를 통해 Vue가 적용될 부분을 선택한다.
  • Vue.createApp 으로 Vue를 생성하고, 객체를 전달한다.

Interpolation

  • createApp 에 date 메소드를 제공함으로 값을 사용할수 있다.
  • data는 객체를 리턴하는 메소드이다.

app.js

Vue.createApp({
 data() {
    return {
        courseGoal: 'Finish the course and learn Vue!'
    };
 }
}).mount("#user-goal")

index.html

<section id="user-goal">
      <h2>My Course Goal</h2>
      <p>{{ courseGoal }}</p>
</section>
  • {{ key }} 구문을 이용해 사용할수 있다.

Interpolation for attribute

  • html attribute 로 interpolation 을 쓰기위해선
    v-bind: 를 앞에 붙혀야 한다.
<p>Learn more <a v-bind:href="vueLink">about Vue</a></p>

메소드 사용하기

  • methods 는 함수를 담는 객체이다.

app.js

Vue.createApp({
 data() {
    return {
        courseGoal: 'Finish the course and learn Vue!',
        vueLink: 'https://vuejs.org/'
    };
 },
 methods: {
    outputGoal() {
        const randomNumber = Math.random();
        if(randomNumber < 0.5){
            return this.courseGoalA
        } else {
            return this.courseGoalB
        }
    }
 }
}).mount("#user-goal")
  • this를 통해 data에 접근할수 있다.

  • 이 외에도 메소드또한 this로 접근 가능하다.

  • Interpolation 과 같이 {{}} 안에서 호출할수 있다.

<p>{{ outputGoal() }}</p>

data에 html 코드 사용하기

data() {
    return {
        courseGoalA: '<h2>Finish the course and study Vue!</h2>',
        courseGoalB: '<h2>Finish the course and study Vue!</h2>',
        vueLink: 'https://vuejs.org/'
    };
 },
  • courseGoalB 처럼 HTML code 를 그대로 사용하기 위해선
<p v-html="outputGoal()"></p>
  • 속성에 v-html 을 추가하면 된다.
  • value로는 사용할 html 구문을 넣는다.

Event binding

  • 클릭과 같은 이벤트에 반응하기 위해선
    v-on:<이벤트> 를 사용한다.
<button v-on:click="counter++">Add</button>
  • 자바스크립트 코드를 그대로 사용하면 된다.
<button v-on:click="add()">Add</button>
  • methods 내의 함수를 바로 호출할수 있다.
  • 함수명만 전달할수도 있다.
    • 자동으로 Argument 가 전달된다.

예시

<input type="text" v-on:input="setName">

setName(e) {
      console.log(e)
      this.name = e.target.value
}

<input type="text" v-on:input="setName($event)">
  • event 가 자동으로 전달되어 사용된다.
  • $event 를 통해 명시적으로 이벤트를 전달할수도 있다.

EventModifier

  • 이벤트에 preventDefault 등 적용하기
  • . 이후에 작성
<form v-on:submit.prevent="submitForm">
  • form에 preventDefault() 를 호출한것과 같이 작동한다.
<button v-on:click.right="reduce(5)">Subtract 5</button>
<button v-on:click.right.prevent="reduce(5)">Subtract 5</button>
<input type="text" v-on:input="setName($event)" v-on:keyup.enter="confirmInput">
  • 마우스의 오른쪽/왼쪽 클릭중 어떤것을 입력으로 받을지
    같은것도 정할수 있다.
  • 키보드의 키를 정할수도 있다.
  • 여러개를 연달아 작성할수도 있다.

input 양방향 값 연결

  • v-model 을 사용해 양방향으로 값을 연결할수 있다.
  • input에서 값을 바꾸거나 값이 바뀌면 input에 적용되도록
    가능하다.
<input type="text" v-model="name">

Computed Property

  • Vue에서 값을 변경했을때 이 변수와 관련된 부분만 새로 렌더링 할수 있게 도울수 있다.
  • createApp 에 computed를 추가한다.
    • methods 와 같이 객체가 들어간다.
computed: {
    fullName() {
      if(this.name === "") {
        return ""
      }
      return this.name + " " + "Karl"
    }
  }
  • data와 유사한 방식으로 사용할수 있다.

watch

  • 메소드가 담길 객체가 주어진다.
  • data의 이름을 가진 메소드를 선언할수 있다.
  • data의 값이 바뀌면 자동으로 호출된다.
  watch: {
    name(newValue, oldValue) {
      if(newValue === '') {
        this.fullName =  '';
      } else {
        this.fullName = this.name + ' ' + this.lastName;
      }
    },
  }
  • name의 값에 Karl 을 뒤에 붙혀 fullName 에 저장한다.
  • newValue 는 변경뒤 값, oldValue 는 변경전 값이다.

사용 예시

  • 변수가 특정 값에 도달시 특정 행동을 하도록 정할수 있다.

Event 표기 줄이기

  • v-on:click 을 @click 으로 줄일수 있다.
  • v-bind:value 를 :value 로 줄일수 있다.

Styling

Dynamic Inline style

  • data 의 값을 기준으로 스타일링할수 있다.
  • inline style을 v-bind:style 로 주고, 객체 형식과 lowerCamelCase 를 통해 작성한다.
v-bind:style="{borderColor: boxSelected ? 'red' : 'gray'}"
- 선택 여부에 따라 border color를 변경하는 예시.

Dynamically add class

  • v-bind:class 로 class 를 지정한다.
  • 3항 연산자를 통해 클래스를 지정할수 있다.
:class="boxSelected ? 'demo active' : 'demo'"
  • 혹은 Inline style 과 같이 객체를 전달하는 방식을 사용한다.
  • 클래스 명이 key, 이를 사용할지에 대한 boolean 값이 value로 사용된다.
:class={
	selected: boxSelected
}
  • :class 와 class 는 같이 존재할수 있다.

Array Syntax

  • 객체의 배열을 :class 에 전달한다.
:class="['demo', {selected: selectedBox}]"
  • 항상 사용되는 class name 을 지정할수 있다.

위 사용되는 객체들은 computed property를 통해 생성할수도 있다.

profile
만능 컴덕후 겸 번지 팬

0개의 댓글