?報錯信息:
Cannot read properties of undefined (reading '$router')
原因:
因為我們在?setup
?里面沒有訪問?this
,所以我們不能直接訪問?this.$router
?或?this.$route
。
解決方案:
作為替代,我們使用?useRouter
?和?useRoute
?函數:
<script setup>
import { useRouter, useRoute } from 'vue-router'const router = useRouter()
const route = useRoute()function pushWithQuery(query) {router.push({name: 'search',query: {...route.query,...query,},})
}
</script>
route
?對象是一個響應式對象。在多數情況下,你應該避免監聽整個?route
?對象,同時直接監聽你期望改變的參數。
<script setup>
import { useRoute } from 'vue-router'
import { ref, watch } from 'vue'const route = useRoute()
const userData = ref()// 當參數更改時獲取用戶信息
watch(() => route.params.id,async newId => {userData.value = await fetchUser(newId)}
)
</script>
請注意,在模板中我們仍然可以訪問?$router
?和?$route
,所以如果你只在模板中使用這些對象的話,是不需要?useRouter
?或?useRoute
?的。
官方文檔:Vue Router 和 組合式 API | Vue Router (vuejs.org)?