익명의 개발노트

[typescript] Vue 클래스 기반 컴포넌트 만드는 법, Prop 전달하는 방법 본문

코딩일기/TIL

[typescript] Vue 클래스 기반 컴포넌트 만드는 법, Prop 전달하는 방법

캡틴.JS 2020. 1. 3. 01:31
반응형

1. 클래스 기반 컴포넌트 (Class base Component)

vue-typescript 클래스구성을 보니 리액트와 비슷해져가는 듯한 느낌을 받았다.

 

기본적으로 뷰 컴포넌트에서 template, script, style 부분에서 script에 반드시 lang="ts"를 명시해주어야 한다.

 

그리고 리액트 처럼, import { Component, Vue } from 'vue-property-decorator' 를 import 해주고, 

 

@Component라는 데코레이터를 사용한다.(데코레이션은 애노테이션 개념보다는 함수로 보면 된다.)

 

그 후에는 클래스 이름 명시와 Vue를 상속 받는다.

<template>
    <div>
        <input type="text" v-model="message">
        <div>{{message}}</div>
    </div>
</template>

<script lang="ts"> //1. ts명시
import {Component, Vue} from 'vue-property-decorator';  //2. import

@Component  //3. Component 데코레이터 명시
export default class Message extends Vue { //4. 클래스 이름과 뷰 상속받기
   message: string = '메세지를 입력해주세요';

}
</script>

<style>

</style>

 

2. Prop 전달하기  

Prop는 import 한 부분에서 Prop을 추가해주고 데코레이터를 클래스 안에다가 명시해준다.(아래참고)

//자식컴포넌트

<template>
    <div>
        {{parentMessage}}
    </div>
</template>

<script lang="ts">
import {Component, Prop, Vue} from 'vue-property-decorator';

@Component
export default class Children extends Vue {
    @Prop() parentMessage?: string;
}
</script>

<style>

</style>

부모에서 자식에게 Prop을 넘길때, 동적, 정적으로 전달이 가능하다. 

//부모컴포넌트

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <message></message>
    <children :parentMessage="message"></children>
  </div>
</template>

<script lang="ts">
// @ is an alias to /src
import {Component, Vue} from 'vue-property-decorator';
import message from '@/components/message.vue';
import children from '@/components/children.vue';

@Component({
  components: {
    message,
    children,
  },
})
export default class Home extends Vue {
   message: string = 'hello world';
}
</script>

 

반응형
Comments