问题
我们都知道在 vue2 中,可以在 mounted 生命周期函数里面使用 this.$route 来获取路由参数,使用 this.$router 来做路由跳转。但是在 vue3 下,是没有 this 实例的,所以这些方法就无法使用了。
例如在 vue2 下获取路由参数以及跳转功能实现,我们可以这样写:
export default {
data() {
return {};
},
created() {
console.log(this.$route.params);
console.log(this.$route.query);
},
methods: {
goTo(path) {
this.$router.push(path);
},
},
};
但是在 vue3 下的 script setup 模式下,通过 this.$route.params 则报错 Cannot read properties of undefined (reading '$route')
<script setup>
import { onMounted } from "vue";
onMounted(function () {
console.log(this); // undefined
console.log(this.$route.params); // Cannot read properties of undefined (reading '$route')
});
</script>
解决
新版的 vue-router 提供的 useRoute()
方法来获取参数,也可以 useRouter()
用来做路由跳转。
<script setup>
import { onMounted } from "vue";
import { useRoute } from 'vue-router'
onMounted(function () {
const route = useRoute();
console.log(route.params.id);
const router = useRouter();
router.push({
name: 'search',
query: {/**/},
})
});
</script>