Reputation: 3464
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 setup
method 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>
Upvotes: 7
Views: 4826
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
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