vue2에서는 코드를 재사용할 수 있는 mixin
만 가지고 있었지만, vue3에서는
composition API
를 활용해 재사용하는 함수인 컴포저블
을 사용할 수 있다.
믹스인은 오버라이딩 문제, 다중 믹스인을 사용하는 경우 코드에 대한 관리가 어려워졌다.
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
}
}