Setup method is not being called
Asked Answered
L

2

7

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>
    
Linkman answered 6/9, 2020 at 12:23 Comment(0)
E
5

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

Ernesternesta answered 6/9, 2020 at 22:59 Comment(0)
P
1

I had the same problem and it was caused by extending the child component. The composition API (setup method) is never called if you extend the component. While the options API lifecycle hooks are called in both components.

// child.js

<script>
import { onMounted } from "vue";

export default {
  name: "ChildComponent",
  setup() {
    console.log('Child - setup()');
    onMounted(() => {
      console.log('Child - mounted (composition API)');
    })
  },
  mounted() {
    console.log('Child - mounted (option API)');
  }
}
</script>
// parent.js

<script>
import ChildComponent from "./child.js";
import { onMounted } from "vue";

export default {
  name: "ParentComponent",
  extends: ChildComponent,
  setup() {
    console.log('Parent - setup()');
    onMounted(() => {
      console.log('Parent - mounted (composition API)');
    })
  },
  mounted() {
    console.log('Parent - mounted (option API)');
  }
}
</script>

OUTPUT

Parent - setup()
Parent - mounted (composition API)
Child - mounted (option API)
Parent - mounted (option API)
Professional answered 8/6, 2021 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.