如果使用
a标签
改变页面会重新发起请求,但是我们点击<RouterLink/>
的时候不会。以下手把手实现一个简单的<RouterLink/>
组件。这节内容与手写<RouterView/>
组件(上一节内容)有一定的联系,建议先看一下。
1、在上一节的基础上加上一个响应式数据(把获取当前路径写在了这里)。
import About from '../view/About.vue'
import Home from '../view/Home.vue'
import {ref} from 'vue'
export default [
{
path: '/',
component: Home
},
{
path: '/about',
component: About
}
]
// 新加内容
export const path = ref(window.location.pathname)
2、对<RouterView/>
组件进行简单的改造
<template>
<div>
<component :is="view"></component>
</div>
</template>
<script setup>
import { computed } from 'vue'
import Router from '../Router';
// 引入path这个响应式数据
import { path } from '../Router';
const view = computed(() => {
// 这里直接使用的path
const res = Router.find(item => item.path == path.value)
return res.component
})
</script>
<style lang="scss" scoped>
</style>
3、创建<RouterLink/>
组件,内容如下:
@click.prevent
阻止a
标签的默认行为,让其被点击时执行push
函数。push
函数里执行的就是改变path
为要加载的页面路径。
<template>
<div>
<a :href="to" @click.prevent="push">
<slot></slot>
</a>
</div>
</template>
<script setup>
import { path } from '../Router';
const props = defineProps({
to: {type: String, required: true}
})
const push = () => {
path.value = props.to
}
</script>
4、在App.vue
中使用。当你点击时不会重新请求。
<RouterLink :to="'/'">首页</RouterLink>
<RouterLink :to="'/about'">关于</RouterLink>
<RouterView></RouterView>
本文由mdnice多平台发布