最近寫vue3+ts和組合式API遇到了上面的問題,程式碼如下:
<template>
</template>
<script setup lang="ts">
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { onMounted } from 'vue'
const store = useStore()
store.dispatch('initMenus')
const route = useRoute()
onMounted(() =>{
console.log(route.path)
})
</script>
<style lang="scss" scoped>
</style>
這個是因為在這個組合式onMounted之前呼叫了store.dispatch('initMenus') 內部包含async/await
解決方法:
If you are using async setup(), make sure to register lifecycle hooks before the first await statement.
只要把程式碼順序調整如下,報錯即可消失:
<template>
</template>
<script setup lang="ts">
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { onMounted } from 'vue'
const route = useRoute()
onMounted(() =>{
console.log(route.path)
})
const store = useStore()
store.dispatch('initMenus')
</script>
<style lang="scss" scoped>
</style>
希望可以幫到你。