报错信息:
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)