前言
在上一篇文章中我们介绍了组件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数组
这里的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
并且提供一个createWebHashHistory
方法,并抛出该方法
别忘了在router文件夹下的index.js引入
我们打印options
看看其是一个什么值
打印可以看出里面有history
对象,以及routes
对象。这里我们把options.routes
交给this.routes
在构造方法中存在一个状态属性this.current
记录当前url状态。是component计算属性的依赖。
在createWebHashHistory
返回的一个是history
对象,我们需要返回一个url,url:window.location.hash.slice(1) || '/'
拿到url,删除第一个字符#
.然后把options.history
给this.history
,状态this.current
里面的值写成this.history.url
.