manidos
manidos

Reputation: 3464

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.

Upvotes: 7

Views: 4826

Answers (2)

MakoBuk
MakoBuk

Reputation: 652

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)

Upvotes: 1

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

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

Upvotes: 5

Related Questions