【问题标题】:Setup method is not being called未调用设置方法
【发布时间】:2020-12-25 01:55:38
【问题描述】:
我使用vue ui(打字稿、babel、linter)创建了一个入门项目。一切正常,但我不太明白如何使 Composition API 的 setupmethod 工作。它根本没有被调用(日志输出为空)这是我卡住的地方。
-
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>
【问题讨论】:
标签:
typescript
vue.js
vuejs3
vue-composition-api
【解决方案1】:
您应该从vue-class-component 导入setup,然后像这样使用它:
<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>
更多详情请查看issue
【解决方案2】:
我遇到了同样的问题,这是由扩展子组件引起的。如果您扩展组件,则永远不会调用 composition API(设置方法)。而 options API 生命周期钩子在两个组件中都被调用。
// 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>
输出
Parent - setup()
Parent - mounted (composition API)
Child - mounted (option API)
Parent - mounted (option API)