Vue3 【路由器】安装引入和使用:简单版

路由管理器,用于构建单页面应用(SPA, Single Page Application)。它允许你在 Vue 应用中定义路由,并根据用户的导航操作动态地加载不同的组件,而无需重新加载整个页面。能看到这里,应该也不用我过多解释什么是路由器了(非物理上的路由器)。

因为我也是新学,不对之处请提出。此文章只能算是笔记,技术有限不过多深入,用最简单的代码把路由器搭建起来,代码自己引伸。话不多说,开始:

先安装路由器:在命令行输入命令

npm i vue-router

 

返回vue-router@版本号证明安装成功。

使用路由器,需要以下四个步骤 ↓

①用于展示区展示用:在src文件夹下新建views文件夹,并在views里新建3个页面文件。(绿色部分为展示区)

aboutPage.vue

<template>
  <div class="about">
    <h2>大家好,这里是展示区</h2>
  </div>
</template>

homePage.vue

<template>
  <div class="home">
    <h2>大家好,这里是首页</h2>
  </div>
</template>

newsPage.vue

<template>
  <div class="news">
    <h2>大家好,这里是新闻页</h2>
  </div>
</template>

②、创建一个路由器,并暴露出去:在src文件夹下新建router文件夹,并在router里新建index.ts的文件。

index.ts:

// 第一步:引入createRouter
import { createRouter, createWebHistory } from 'vue-router'
//引入组件
import home from '@/components/homePage.vue'
import about from '@/components/aboutPage.vue'
import news from '@/components/newsPage.vue'

//第二部:创建路由器
const router = createRouter({
  history: createWebHistory(),//路由器的工作模式
  routes: [
    {
      path:'/01',
      component: home
    },
    {
      path:'/02',
      component: about
    },
    {
      path:'/03',
      component: news
    }
  ], // 配置路由规则的数组
})

export default router // 暴露出去router

③在main.ts引入刚才创建的路由器。

main.ts:

// 引入createApp用于创建应用
import { createApp } from 'vue'
//引入App根组件
import App from './App.vue'
//引入路由器
import router from './router/index.ts'

const app=createApp(App)
//使用路由器
app.use(router)
//挂载到id为app的标签上
app.mount('#app')

④在App.vue父组件文件进行布局

App.vue

<script setup lang="ts">
// 引入路由组件
import { RouterView,RouterLink } from 'vue-router';
</script>

<template>
<div>
  <!--标题-->
  Vue路由测试
</div>

<div>
  <!--按钮-->
  <RouterLink to="/01" active-class="active">
    首页
  </RouterLink>

  <RouterLink to="/03" active-class="active">
    新闻
  </RouterLink>

  <RouterLink to="/02" active-class="active">
    关于
  </RouterLink>
</div>

<div>
  <!--展示区 占位-->
<RouterView></RouterView>
</div>
</template>

<style scoped>
<!--样式自行添加,简单点可以把代码给AI,让它给你出样式-->
</style>

在此就完成了最简单的路由引入搭建,测试运行。

npm run dev

注:上面的代码测试通过。默认你已经安装了 VScode,并安装了Vue3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值