import { useRouter } from 'vue-router'
const use_router = useRouter()
use_router.push('/pathName')
import router from '@/router'
router.push('/pathName')
在vue3中,使用在组件的带setup属性的script标签内
<script setup>
import { useRouter } from "vue-router"
const router = useRouter()
</script>
适用于vue3和vue2版本,可以使用在任意文件中(js文件和vue文件)
main.js中
1.在vue3中,不能和vue2一样使用this.$router,必须通过导入路由API来使用
import { useRouter } from "vue-touter"
2.useRouter也是一个函数,需要在setup里定义一个变量来获取当前路由
const router = useRouter()
3.此时,就可以通过定义的router来操作路由进行页面的跳转等操作
// 跳转首页
router.push({
name: 'home',
})
// 返回上一页
router.back()
1.在vue3中,不能和vue2一样使用this.$route(this.$route.params),也必须通过导入路由API来使用
import { useRoute } from "vue-router"
2.在setup里定义一个变量来获取当前的路由信息
const route = useRoute()
3.此时,就可以通过定义的route来获取当前的路由信息
// 获取路由名称
console.log(route.name)
// 获取路由参数
console.log(route.params.id)
// 获取路由元信息
console.log(route.meta.xxx)
{
path: '/test/:id',
name: 'test',
component: () => import('../views/TestView.vue')
}
<template>
<div>
{{ id }}
</div>
</template>
<script setup lang="ts">
import { onMounted, toRefs, ref } from 'vue'
import { useRoute } from 'vue-router';
// 接收路由传参
let route = useRoute()
console.log('route->', route);
let {params} = toRefs(route)
let id = ref(0);
onMounted(()=>{
console.log('id=' + params.value.id);
id.value = params.value.id;
})
</script>
<style scoped>
</style>
{
path: '/test1/:id',
name: 'test1',
component: () => import('../views/Test1View.vue')
}
import { onMounted, toRefs, ref } from 'vue'
import { useRoute,useRouter } from 'vue-router';
// 接收路由传参
let route = useRoute()
let router = useRouter()
console.log('route->', route);
let {params} = toRefs(route)
let id = ref(0);
const jumpTo = () => {
router.push('/test/999');
}
onMounted(()=>{
console.log('id=' + params.value.id);
id.value = params.value.id;
})
{
path: '/test2',
name: 'test2',
component: () => import('../views/Test1View.vue')
}
<RouterLink to="/test2?id=1">测试1</RouterLink>
<template>
<div>
</div>
</template>
<script setup lang="ts">
import { onMounted, toRefs, ref } from 'vue'
import { useRoute,useRouter } from 'vue-router';
// 接收路由传参
let route = useRoute()
console.log('route->', route);
onMounted(()=>{
//
console.log('接参:id = ', route.query.id);
})
</script>
<style scoped>
</style>