$router

注意:useRouter执行一定要放在setup方法内的顶部或者其他位置,不能放在下面setup的函数里面执行,否则作用域改变useRouter执行是undefined

  • useRouter 的用法 在前端开发中,我们经常需要程序处理用户的路由导航,这时候就需要用到 useRouter。它是一个用于获取当前路由实例的函数,我们可以调用这个函数来获取路由实例,然后进行路由导航。

  • useRoute 的用法 除了需要导航路由之外,我们还需要获取一些路由信息,这时候就需要用到 useRoute。它是一个用于获取当前路由对象的函数,我们可以调用这个函数来获取路由的参数、查询参数等信息。

  • 传递参数

import { createRouter,createWebHistory,createWebHashHistory } from 'vue-router'
import File1 from '../components/File1.vue'
import File2 from '../components/File2.vue'

const routes = [
    {
        path: '/',
        component:File1
    },
    {
        path: '/file2/:username/abc/:userid', //注意看这个
        component:File2
    }
]

const router = createRouter({
    history: createWebHistory(),
    // history:createWebHashHistory(),
    routes,
})

export default router;
  • useRouter
    • useRouter()返回的是object, 类似于vue2的this.$router
  • getCurrentInstance

vue3获取当前this

  • 路由传递参数

<template>
  <div>user</div>
  <p>uid: {{ uid }}</p>
</template>
  
<script>
import { defineComponent } from "vue";
import { useRouter } from "vue-router";
  
export default defineComponent({
  name: "User",
  setup() {
    const router = useRouter();
    const uid = router.currentRoute.value.params.uid;
    return {
      // 返回的数据
      uid,
    };
  },
});
</script>



<template>
    <div>
        这是文件二
    </div>
</template>

<script setup lang="ts">
import {getCurrentInstance,onMounted } from 'vue'

const instance  = getCurrentInstance() 
if (instance != null) {
    const _this = instance.appContext.config.globalProperties //vue3获取当前this
    
onMounted(() => {   
    console.log(_this.$route.params)
  })
}
</script>

<style scoped>

</style>

  • 404 Not Found路由
import { createRouter,createWebHistory,createWebHashHistory } from 'vue-router'
import File1 from '../components/File1.vue'
import File2 from '../components/File2.vue'
import NotFound from '../components/NotFound.vue'
import UserGeneric from '../components/UserGeneric.vue'


const routes = [
    {
        path: '/',
        component:File1
    },
    {
        path: '/file2/:username/abc/:userid',
        component:File2
    },
    // 将匹配所有内容并将其放在 `$route.params.pathMatch` 下
    {
        path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound
    },
    // 将匹配以 `/user-` 开头的所有内容,并将其放在 `$route.params.afterUser` 下
    {
        path: '/user-:afterUser(.*)', component: UserGeneric
    },
]

const router = createRouter({
    history: createWebHistory(),
    // history:createWebHashHistory(),
    routes,
})

export default router;


  • notFound
<template>
    <div>
        404 not found
    </div>
</template>

<script setup lang="ts">
import {getCurrentInstance,onMounted } from 'vue'

const instance  = getCurrentInstance() 
if (instance != null) {
    const _this = instance.appContext.config.globalProperties //vue3获取当前this
    
onMounted(() => {
    console.log(_this.$route.params)
  })
}
</script>

<style scoped>

</style>

  • 嵌套路由
import { createRouter,createWebHistory,createWebHashHistory } from 'vue-router'
import File1 from '../components/File1.vue'
import File2 from '../components/File2.vue'
import NotFound from '../components/NotFound.vue'
import UserGeneric from '../components/UserGeneric.vue'
import Children1 from '../components/Children1.vue'
import Children2 from '../components/Children2.vue'



const routes = [
    {
        path: '/',
        component: File1,
        
    },
    {
        path: '/file2',
        component: File2,
        children: [  //使用嵌套路由
            {
                path: 'children1',
                component:Children1
            },
            {
                path: 'children2',
                component:Children2
            },
        ]
    },
    {
        path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound
    },
    {
        path: '/user-:afterUser(.*)', component: UserGeneric
    },
]

const router = createRouter({
    history: createWebHistory(),
    // history:createWebHashHistory(),
    routes,
})

export default router;


编程式导航

  • 除了使用 < router-link/> 创建 a 标签来定义导航链接,
  • router.push()
  • **router.replace()**作用类似于 router.push,唯一不同的是,它在导航时不会向 history 添加新记录
  • **$router.go(-1)**相当于点击回退一次
<template>
    <div>
       404 not found
    </div>
</template>

<script setup lang="ts">
import {getCurrentInstance,onMounted } from 'vue'

const instance  = getCurrentInstance() 
if (instance != null) {
    const _this = instance.appContext.config.globalProperties //vue3获取当前this

    // 一。router.push的使用: 
    // 1.字符串路径
    // _this.$router.push('/file2/children2')

    // 2.带有路径的对象
    // _this.$router.push({path:'/file2/children2'})

    // 3.命名的路由,并加上参数,让路由建立 url
    // _this.$router.push({name:'file2',params:{username:'children2'}})

    // 4.带查询参数,结果是 /register?plan=private
    // _this.$router.push({ path: '/file2/children2', query: {userid:'123'} })

    // 二。router.replace的使用:
    // _this.$router.replace('/file2/children1')

    // 三。router.go的使用:
    _this.$router.go(-1)  //相当于点击回退一次

    onMounted(() => {
    console.log(_this.$route.params)
  })
}
</script>

<style scoped>

</style>