gomstory

Vue2.7 Mixin -> Composable 본문

Vue.js

Vue2.7 Mixin -> Composable

gommmmm 2024. 8. 23. 10:43

 

회사에서 Vue2.x 프로젝트를 Vue3(3.3.4)로 마이그레이션하는 작업을 진행하고있다.

Mixin을 남발하는 프로젝트가 하나 있어서 Composition API로 전환하기 위해 테스트를 해봤다.

 

https://vuejs.org/api/composition-api-setup.html

 

Vue.js

Vue.js - The Progressive JavaScript Framework

vuejs.org

 

대충 구글링하고 냅다 

npm install @vue/composition-api --save

했는데 오류남

 

치기 전에 생각하자.

 

기존 Mixin 코드

<template>
 <div>
  <button @click="testFunc">
   mixin test
  </button>
 </div>
</template>

<script>
import mixinTest from "@/mixin/mixinTest"

export default {
  name: 'TestComponent',
  mixins: [mixinTest],
  methods: {
    testFunc() {
      this.testData = true
      this.methodTest()
    }
  }
}
</script>
let mixinTest = {
    watch:{
        testData : 'watchTest'
    },
    methods:{
        methodTest() {
            console.log("method call ", this.testData)
        },
        watchTest() {
            console.log("watch call ", this.testData)
        }
    },
    data () {
        return {
            testData : false,
        }
    },
}
export default mixinTest

 

Composition API

<template>
 <div>
  <button @click="testFunc">
   mixin test
  </button>
 </div>
</template>

<script>
import { compositionTest } from "@/composables/compositionTest"

export default {
 name: 'TestComponent',
 setup() {
    let { testData, methodTest } = compositionTest()
    function testFunc() {
      testData.value = true
      methodTest()
    }
    return{
      testFunc
    }
  },
}
</script>
// compositionTest.js
import { ref, watch } from 'vue'

export function compositionTest() {
    // data
    const testData = ref(false)
    // methods
    function methodTest() {
        console.log("method call ", testData.value)
    }
    function watchTest() {
        console.log("watch call ", testData.value)
    }
    // watch
    watch([testData], watchTest)
    return {
        testData,
        methodTest
    }
}

 

정상동작 확인

갈길이 멀다