Search code examples
typescriptvue.jsvuejs3vue-composition-apivue-script-setup

Setup method is not being called


I've created a starter project with vue ui (typescript, babel, linter). Everything works fine, but I can't quite understand how to make Composition API's setupmethod to work. It's simply not being called (log output is empty) Here's where I'm stuck.

  • vue: 3.0.0-rc.10

  • vue-cli: 4.5.4

    <script lang="ts">
     import { Options, Vue } from 'vue-class-component'
     import HelloWorld from './components/HelloWorld.vue'
    
     @Options({
       components: {
         HelloWorld
       },
       setup () {
         console.log('SETUP HERE')
       }
     })
     export default class App extends Vue {
       setup () {
         console.log('SETUP THERE')
       }
     }
     </script>
    

Solution

  • You should import setup from vue-class-component then use it like :

    <template>
      <div>Count: {{ counter.count }}</div>
      <button @click="counter.increment()">+</button>
    </template>
    
    <script lang="ts">
    import { ref, reactive, onMounted } from 'vue'
    import { Vue, setup } from 'vue-class-component'
    
    function useCounter () {
      const count = ref(0)
    
      function increment () {
        count.value++
      }
    
      onMounted(() => {
        console.log('onMounted')
      })
    
      return {
        count,
        increment
      }
    }
    
    export default class Counter extends Vue {
      counter = setup(() => useCounter())
    }
    </script>
    

    for more details please check this issue