실무/vue.js 실무 기능

15. 비지니스 로직을 class로 만들고, 그 클래스를 Vue 컴포넌트에서 사용

DEV-Front 2024. 1. 14. 18:46
반응형

Vue.js와 TypeScript를 사용하여 비지니스 로직을 클래스로 만들고, 그 클래스를 Vue 컴포넌트에서 사용하는 예제

 

 

TypeScript로 작성된 클래스 파일(BusinessLogic.ts)

// BusinessLogic.ts

export default class BusinessLogic {
  private data: string;

  constructor() {
    this.data = '';
  }

  setData(value: string): void {
    this.data = value;
  }

  getData(): string {
    return this.data;
  }

  processData(): string {
    // 비지니스 로직을 추가하거나 가정합니다.
    return `Processed: ${this.data}`;
  }
}

 


그런 다음, Vue 컴포넌트에서 이 클래스를 import하여 사용하는 예제 (MyComponent.vue)

<!-- MyComponent.vue -->

<template>
  <div>
    <h1>{{ result }}</h1>
    <button @click="performBusinessLogic">Perform Business Logic</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import BusinessLogic from './BusinessLogic';

export default defineComponent({
  data() {
    return {
      result: '',
    };
  },
  methods: {
    performBusinessLogic() {
      const logicInstance = new BusinessLogic();
      logicInstance.setData('Hello, TypeScript!');
      const processedData = logicInstance.processData();
      this.result = processedData;
    },
  },
});
</script>
  • 이 예제에서 BusinessLogic 클래스는 데이터를 설정하고, 가져오며, 처리하는 세 가지 메서드를 갖고 있습니다.
  • 그리고 Vue 컴포넌트에서는 해당 클래스를 import하여 버튼 클릭 이벤트에서 비지니스 로직을 수행하고 결과를 화면에 표시하고 있습니다.
  • 이러한 방식으로 클래스를 사용하면 코드를 모듈화하고 재사용성을 높일 수 있습니다
반응형