Vue Router 全面详解--【一、从零开始搭建Vue Router,一步一步的掌握Vue Router】

大家好!欢迎收看Vue Router 全面全面详解,本文将从全方位的介绍Vue Router 的使用

Vue Router 基础使用

一、首先来新建几个页面吧(项目初始化过程就不介绍了,Vite 直接创建就好)

目录结构如下:

二、安装vue-router

执行pnpm add vue-router@4 安装

三、新建router文件夹,

文件夹下index.js

四、编写index.js 内容,也是vue-router 使用的核心代码

  1. 首先引入 vue-router

import { createRouter, createWebHistory } from 'vue-router'

  1. 路由列表
js 复制代码
const routes = [
  {
    path: '/',
    name: "Index",
    component: Index
  },
  {
    path: '/newlist',
    name: "NewList",
    component: NewList
  },
  {
    path: '/article-list',
    name: "ArticleList",
    component: ArticleList
  }
]

路由列表主要有三个参数 path: 页面访问的路径,name: 组件名称, compoents 路由指向的组件

  1. 导出 createRouter的执行
js 复制代码
export default createRouter({
  history: createWebHistory(),
  routes
})

注意: history 有两种模式,一种是history 模式, createWebHistory 函数执行,如果想使用hash模式,createWebHashHistory 执行即可, 两者主要的区别,hash访问路径会 会带# ,history 不会,一般都使用history 较多。 来看下index.js 的完整代码

js 复制代码
import { createRouter, createWebHistory } from 'vue-router'

import Index from '@/views/index.vue'
import NewList from '@/views/new/NewList.vue'
import NewDetail from '@/views/new/NewDetail.vue'
import ArticleList from '@/views/article/ArticleList.vue'
import ArticleLDetail from '@/views/article/Article.vue'

const routes = [
  {
    path: '/',
    name: "Index",
    component: Index
  },
  {
    path: '/newlist',
    name: "NewList",
    component: NewList
  },
  {
    path: '/new-detail',
    name: "NewDetail",
    component: NewDetail
  },
  {
    path: '/article-list',
    name: "ArticleList",
    component: ArticleList
  },
  {
    path: '/article-detail',
    name: "ArticleLDetail",
    component: ArticleLDetail
  }
]

export default createRouter({
  history: createWebHistory(),
  routes
})

五、路由视图

在App.vue 使用router-view 组件来渲染出路由指定组件,这是vue-router 自带的组件,不需要再额外注册 看下 App.vue组件的代码

vue 复制代码
<script setup>
</script>

<template>
  <div>
    <nav>
      <a href="/">首页</a>
      <a href="/article-list">文章</a>
      <a href="/newlist">新闻</a>
    </nav>
    <router-view></router-view>
  </div>
</template>

<style scoped>
  nav {
    display: flex;
    width: 480px;
    justify-content: space-between;
  }
</style>

一个基本的路由使用就配置完成了,现在我们就在地址栏输入路由列表配置里面有的path 路径看看效果

输入: http://localhost:5173/

点击新闻http://localhost:5173/newlist

点击文章: http://localhost:5173/article-list

现在我们就完成了一个Vue Router 的基本使用

我们是通过普通a 标签的href 来跳转的,他会刷新整个页面,体验不太好,不符合单页面应该用的特点,这时候该router-link出场了。

我们将App.vue 里面的a 标签

html 复制代码
<a href="/">首页</a>
<a href="/article-list">文章</a>
<a href="/newlist">新闻</a>

改成 router-link, 且将href改成 to 具体代码如下

html 复制代码
<router-link to="/">首页</router-link>
<router-link to="/article-list">文章</router-link>
<router-link to="/newlist">新闻</router-link>

现在我们再来点击导航切换,就不会刷新整个页面了,只会刷新页面变化的内容。

动态路由

我们现在准备两个数据,一个是文章列表的数据,一个是新闻列表的数据

文章数据:

js 复制代码
export default [
  {
    id: 1,
    title: '静夜诗',
    detail: `床前/明月/光,疑是/地上/霜。举头/望/明月,低头/思/故乡。`
  },
  {
    id: 2,
    title: '草',
    detail: `离离原上草,一岁一枯荣。野火烧不尽,春风吹又生。远芳侵古道,晴翠接荒城。又送王孙去,萋萋满别情。`
  },
  {
    id: 3,
    title: '咏鹅',
    detail: `鹅鹅鹅,曲项向天歌。白毛浮绿水,红掌拨清波。`
  }
]

新闻数据:

js 复制代码
export default [
  {
    id: 1,
    title: '今天天气怎么样',
    detail: `1、打开心窗,让阳光和风儿,给自己一个贴心拥抱,心灵就不会被寒冷冰封。
             2、和煦的阳光,透过稠密的树叶洒落下来,成了点点金色的光斑。
            3、太阳刚刚从东方升起,小鸟在树上歌唱,孩子们在森林中欢乐地游戏的生活情景。`
  },
  {
    id: 2,
    title: '深圳旅游景点',
    detail: `世界之窗正像它的名字那样,是一扇展现世界名胜的窗口的主题乐园,里面有世界各知名景点的缩影。除外,这里还有世界各地的风情表演,日本茶道、非洲风情歌舞秀等,等待你的观赏。`
  },
  {
    id: 3,
    title: '卡丁车',
    detail: `6千米赛道随便玩`
  }
]

现在来改造下文章列表页面和新闻列表页面

文章列表:

vue 复制代码
<template>
  <ul>
    <li v-for="item in data" :key="item.id">
      <router-link to="/detail">{{ item.title }}</router-link>
    </li>
  </ul>
</template>
<script setup>
import data from './data'
</script>
<style scoped>
  ul,
  ul li {
    margin: 0;
    padding: 0
  }
  ul {
    margin-top: 30px;
  }
  ul li {
    list-style: none;
    text-align: left;
    padding-top: 10px;
    border-bottom: 1px solid #ddd;
  }
  ul li a {
    color: #232323;
  }
</style>

效果如下:

新闻列表

vue 复制代码
<template>
  <ul>
    <li v-for="item in data" :key="item.id">
      <router-link to="/new-detail">{{ item.title }}</router-link>
    </li>
  </ul>
</template>
<script setup>
  import data from './data'
</script>
<style scoped>
ul,
  ul li {
    margin: 0;
    padding: 0
  }
  ul {
    margin-top: 30px;
  }
  ul li {
    list-style: none;
    text-align: left;
    padding-top: 10px;
    border-bottom: 1px solid #ddd;
  }
  ul li a {
    color: #232323;
  }
</style>

效果如下

现在我们来点击列表,肯定会跳到同一个页面, 且每一篇文章内容都相同,新闻列表也一样每条新闻内容都是一个,要想跳转到不一样的内容页面,怎么办呢!新建和列表一样多的详情页面吗? 肯定是不现实的。该怎么办呢? 这个时候动态路由就该出场了。

  1. 先来到router 下面的index.js, 将文章详情的 path 改成 /article-detail/:id, 将新闻详情的path 改成 /new-detail/:id

具体代码如下:

js 复制代码
import { createRouter, createWebHistory } from 'vue-router'

import Index from '@/views/index.vue'
import NewList from '@/views/new/NewList.vue'
import NewDetail from '@/views/new/NewDetail.vue'
import ArticleList from '@/views/article/ArticleList.vue'
import ArticleLDetail from '@/views/article/Article.vue'

const routes = [
  {
    path: '/',
    name: "Index",
    component: Index
  },
  {
    path: '/newlist',
    name: "NewList",
    component: NewList
  },
  {
    path: '/new-detail/:id',
    name: "NewDetail",
    component: NewDetail
  },
  {
    path: '/article-list',
    name: "ArticleList",
    component: ArticleList
  },
  {
    path: '/article-detail/:id',
    name: "ArticleLDetail",
    component: ArticleLDetail
  }
]

export default createRouter({
  history: createWebHistory(),
  routes
})

再将新闻列表中的router-link 的to 改成:to="/new-detail/ <math xmlns="http://www.w3.org/1998/Math/MathML"> i t e m . i d ' " ' ,文章列表中的 t o 改成 ' : t o = " ' / a r t i c l e − d e t a i l / {item.id}`"`,文章列表中的to 改成`:to="`/article-detail/ </math>item.id'"',文章列表中的to改成':to="'/article−detail/{item.id}"

接下来看详情页面,详情页面就需要接收参数了,使用params 进行接收

首先从 vue-router 导入一个函数 import { useRoute } from 'vue-router'

引入文章数据:

import data from './data'

声明一个变量接收 useRoute执行结果 const route = useRoute()

声明一个变量存储当前文章对象, onMounted 里面接收参数,通过接收到的参数筛选出当前的文章对象

js 复制代码
onMounted(() => {
    const id = route.params.id
    article.value = data.find(item => item.id === id)
  })

模板修改

js 复制代码
<h1>{{ article.title }}</h1>
<p>{{ article.detail }}</p>

来看下文章详情的完整代码

js 复制代码
<template>
  <h1>{{ article.title }}</h1>
  <p>{{ article.detail }}</p>
</template>
<script setup>
  import { ref, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import data from './data'
  const route = useRoute()
  const article = ref({})
  onMounted(() => {
    const id = route.params.id
    article.value = data.find(item => item.id == id)
  })
</script>
<style></style>

看下效果

新闻详情代码也差不多

js 复制代码
<template>
  <h1>{{ newDetail.title }}</h1>
  <p>{{ newDetail.detail }}</p>
</template>
<script setup>
  import { ref, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import data from './data'
  const route = useRoute()
  const newDetail = ref({})
  onMounted(() => {
    const id = route.params.id
    newDetail.value = data.find(item => item.id == id)
  })
</script>
<style>
p {
  max-width: 480px;
}
</style>

效果

路由另一种跳转方式(push 和replace)

1. 首先来看push

我们现在将文章列表的router-link标签改为a标签,不过现在不用href 跳转了,用javascript:void(0)为协议阻止a标签默认行为。 添加点击事件@click="lindDetail(item.id)"

从vue-router 中引入userRouter import { useRouter } from 'vue-router'

声明一个变量接收useRouter执行结果: const router = useRouter()

定义linkDetail 函数处理跳转

js 复制代码
function lindDetail(id) {
  router.push({ name: 'ArticleLDetail',params: { id }})
}

来看下文章列表完整代码:

js 复制代码
<template>
  <ul>
    <li v-for="item in data" :key="item.id">
      <a href="javascript:void(0)" @click="lindDetail(item.id)">{{ item.title }}</a>
    </li>
  </ul>
</template>
<script setup>
import { useRouter } from 'vue-router'
import data from './data'
const router = useRouter()
function lindDetail(id) {
  router.push({ name: 'ArticleLDetail',params: { id }})
}
</script>
<style scoped>
  ul,
  ul li {
    margin: 0;
    padding: 0
  }
  ul {
    margin-top: 30px;
  }
  ul li {
    list-style: none;
    text-align: left;
    padding-top: 10px;
    border-bottom: 1px solid #ddd;
  }
  ul li a {
    color: #232323;
  }
</style>

注意push 里面的name 属性对应的值是路由列表对应的name, params: { id} 是传参数的方式

来看看效果,和之前一样

2.replace 跳转

我们用新闻列表来展示,其实和push使用方式差不多,将push方法改成replace 即可 ,来看下具体代码:

vue 复制代码
<template>
  <ul>
    <li v-for="item in data" :key="item.id">
      <a href="javascript:void(0)" @click="lindDetail(item.id)">{{ item.title }}</a>
    </li>
  </ul>
</template>
<script setup>
import { useRouter } from 'vue-router'
import data from './data'
const router = useRouter()
function lindDetail(id) {
  router.replace({ name: 'NewDetail',params: { id }})
}
</script>
<style scoped>
ul,
  ul li {
    margin: 0;
    padding: 0
  }
  ul {
    margin-top: 30px;
  }
  ul li {
    list-style: none;
    text-align: left;
    padding-top: 10px;
    border-bottom: 1px solid #ddd;
  }
  ul li a {
    color: #232323;
  }
</style>

看下效果

push 方法和repleace 都能实现跳转,使用方式都差不多,那有什么区别吗? 有的, push 是直接添加记录, repleace是直接替换历史记录,主要表现在你点击浏览器前进回退时会有差异。

总结:

  1. 今天主要学习了Vue Router 搭建的整个流程
  2. router-link 实现无刷新跳转
  3. 动态路由实现列表跳转详情,
  4. 另外两种跳转页面的方式, push和replace, 以及他们的区别

今天就到这里了,下次见

相关推荐
奶昔不会射手9 天前
vue3项目,本地页面正常显示,打包后页面空白
vue3·vue-router
kidding72322 天前
前端的面试题
前端·前端框架·vue-router·history·hash·abstract·v-bind
又言又语1 个月前
【Vue3】编程式路由导航
vue·vue3·vue-router·编程式路由导航
又言又语1 个月前
【Vue3】配置路由规则props
vue·vue3·vue-router·props·路由传参
又言又语1 个月前
【Vue3】路由基础
vue·vue3·路由·vue-router
Java_慈祥2 个月前
懂个锤子Vue VueRouter路由深入浅出
前端·vue.js·vue-router
三六2 个月前
Vue 3 的5种路由守卫
前端·vue.js·vue-router
eiko莉2 个月前
vue权限路由-权利分配游戏
vue.js·vue-router
呆同学2 个月前
掌握Vue Router:轻松实现单页面应用的路由管理
前端·vue-router