Composables

채윤·2022년 6월 21일
0

컴포저블(Composables)이란?

vue2에서는 코드를 재사용할 수 있는 mixin만 가지고 있었지만, vue3에서는
composition API를 활용해 재사용하는 함수인 컴포저블을 사용할 수 있다.

  • composition API는 특정 기능을 갖는 함수를 뜻하고 API처럼 사용할 수 있게 해주는 것을 말한다.
  • 이는 코드에 대한 재사용성효율적으로 할 수 있게 해준다.
  • 연관성 있는 로직을 같이 구현할 수 있어 코드가 간결해지고 유지 관리쉬워진다.

믹스인은 오버라이딩 문제, 다중 믹스인을 사용하는 경우 코드에 대한 관리가 어려워졌다.

Mixin vs Composables

  • 믹스드인은 오버라이딩이 발생하면 데이터가 손실될 우려가 있다. 컴포저블은 변수의 이름을 바꿀 수 있다.

Mixin

//MyComponent.vue

import ProductMixin from './ProductMixin' // name = AirMax
import BrandMixin from './BrandMixin' // name = Nike
import UserMixin from './UserMixin' // name = John Doe
export default{
    mixins:[ProductMixin, BrandMixin, UserMixin],
    created(){  
        // Actually I'm not so lucky,
        // yeah I found the name in ProductMixin
        // but turns out UserMixin had a name too
        console.log(this.name) // John Doe
    }
}

Composables

//MyComponent.vue
import useProduct from './useProduct' // name = AirMax
import useBrand from './useBrand' // name = Nike
import useUser from './useUser' // name = John Doe
export default{
    setup(){
        const { name: productName } = useProduct()
        const { name: brandName } = useBrand()
        const { name: userName } = useUser()

        return { productName, brandName, userName }
  }
    created(){
        // Yay! Nothing is lost and I can get the name of each of the things
        // together in my component but when writing the composables
        // I don't have to think at all about what variable names might collide
        // with names in other composables
        console.log(this.productName)
        console.log(this.brandName)
        console.log(this.userName)
    }
}

컴포저블 전역 상태

//CounterMixins.js
export default{
    data(){
        return { count: 0 }
    },
    methods:{
        increment(){
            this.count ++
        }
    }
}
//useCounter.js
import {ref, readonly} from 'vue'
export default () => {
  const count = ref(0)
    const increment = ()=> count.value++

    return {
        count: readonly(count), 
        increment
    }
}
//useCounter.js
import {ref, readonly} from 'vue'
const count = ref(0)
export default () => {
    const increment = ()=> count.value++

    return {
        count: readonly(count), 
        increment
    }
}
  • 믹스인은 모든 데이터가 사용되는 인스턴스에 대해 항상 재설정된다.
    예를 들어 count를 통해 1을 증가시켜로 할 경우, 모든 구성 요소가 동작하는 것이 아닌 동작을 하게끔 구현한 곳에서만 동작하게 된다.
  • vuex와 같이 전역 상태처럼 동작하길 원할 경우에는 함수의 바깥쪽으로 옮기게 되면 전역적으로 사용할 수 있다.
profile
프론트엔드 개발자

0개의 댓글