手撕Vue.js中的Vue-router(二):实现`router-view`(一)

172 阅读2分钟

前言

     在上一篇文章中我们介绍了组件router-link,在这篇文章中我们将介绍另一个组件router-view.在 Vue.js 应用中,router-view 作为一个特殊的占位符,用于动态渲染与当前激活的路由相对应的组件。这意味着,当 URL 发生变化时,router-view 渲染的组件也会相应地更新,而无需整个页面重新加载。

RouterView

     首先我们先在grouter文件夹下创建文件RouterView.vue文件

<template>
    <component :is="component"></component>
</template>

<component :is="component"></component>这是一个动态组件,组件router-view的实现就是依据它来实现的,使用<component>占位,来实现动态组件。既然<component>是一个动态组件,所以这里我们的component需要一个响应式变量,那么这个响应式变量是如何获取的呢?我们可以使用useRouter拿到router.url再去到配置数组routes中拿到component.这里我们可以这样实现。首先实例化useRouter,然后使用计算属性实现响应式

<script setup>
import {computed} from 'vue'

// 如何获取到component
// userRouter  拿到router.url 再去到数组routes中 拿到component :About
let router = useRouter()  //拿到router对象
//动态的component 响应式 计算属性对数据进行计算,保证更新
const component = computed(()=>{
    const route = router.routes.find(
        (route) => route.path === router.url
    )
    return route?route.component:null
})
</script>

在我们的router文件下的配置文件index.js中有routes数组

image.png

这里的find是es6中数组中的一个遍历方法。我们这个计算属性一定会返回一个动态组件没有找到的话就返回null; 在router文件夹下的配置文件index.js

import {createRouter,createWebHashHistory} from './grouter/index.js'
import Home from '../views/Home.vue'
import About from '../views/About.vue'

const routes = [
    {
        path:'/',
        component:Home
    },
    {
        path:'/about',
        component:About
    }
]

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

export default router

这里我们创建router对象,使用createRouter,传入history参数,以及routes参数。回到grouter文件夹下的index.js配置文件中,存在一个构造函数constructor方法,这个方法我们传入一个参数options

image.png

并且提供一个createWebHashHistory方法,并抛出该方法

image.png

别忘了在router文件夹下的index.js引入

image.png

我们打印options看看其是一个什么值

image.png

打印可以看出里面有history对象,以及routes对象。这里我们把options.routes交给this.routes 在构造方法中存在一个状态属性this.current记录当前url状态。是component计算属性的依赖。 在createWebHashHistory返回的一个是history对象,我们需要返回一个url,url:window.location.hash.slice(1) || '/'拿到url,删除第一个字符#.然后把options.historythis.history,状态this.current里面的值写成this.history.url.