Vue-router

router的使用(5+2)

5个基础步骤:

1.在终端执行yarn add vue-router@3.6.5,安装router插件

yarn add vue-router@3.6.5

2.在文件的main.js中引入router插件

import VueRouter from 'vue-router'

3.在main.js中安装注册Vue.use(Vue插件)

Vue.use(VueRouter)

4.在main.js中创建路由对象

const router = new VueRouter()

5.注入到new Vue中,建立关联

new Vue({
  render: h => h(App),
  router: router
}).$mount('#app')

2个核心步骤:

1.创建需要的组件(views目录),配置路由规则

import Find from './views/Find.vue'
import Friend from './views/Friend.vue'
import My from './views/My.vue'
Vue.use(VueRouter)//VueRouter插件初始化

 
const router = new VueRouter({
  // 路由规则
  routes:[
    {path:'/find',component:Find},
    {path:'/my',component:My},
    {path:'/friend',component:Friend}
  ]
})

2.准备导航链接,配置路由出口

<template>
  <div>
    <div>
      <a href="#/find">发现音乐</a>
      <a href="#/my">我的音乐</a>
      <a href="#/friend">我的朋友</a>
    </div>
    <div>
      <router-view></router-view>
    </div>
  </div>
</template>

Vue Router 提供了以下常用的标签和功能:

  1. <router-link>:渲染一个 <a> 标签,点击时会导航到指定的路由。
  2. <router-view>:用于渲染匹配到的路由组件。
  3. router-link 组件的 to 属性:用于指定要跳转的目标路由,可以是字符串或对象。
  4. router-view 组件:用于根据当前路由匹配到的组件进行渲染。

路由的封装抽离

目标:将路由模块抽离出来

好处:拆分模块,利于维护

在src目录下创建router文件,在文件中创建index.js文件,将main.js中的路由模块抽离到index.js文件中

import VueRouter from 'vue-router'
import Find from '../views/Find.vue'
import Friend from '../views/Friend.vue'
import My from '../views/My.vue'

import Vue from 'vue'
Vue.use(VueRouter)//VueRouter插件初始化

 
const router = new VueRouter({
  // 路由规则
  routes:[
    {path:'/find',component:Find},
    {path:'/my',component:My},
    {path:'/friend',component:Friend}
  ]
})

export default router

在main.js中引入index.js文件

import router from './router'

声明式导航-导航链接

需求:实现导航高亮效果

vue-router提供了一个全局组件router-link(取代a标签)

  1. 能跳转,配置to属性指定路径(必须)。本质还是a标签,to无需#
  2. 能高亮,默认就会提供高亮类名,可以直接设置高亮样式

1.router-link-active 模糊匹配(用的多)

to = '/my' 可以匹配/my      /my/a      /my/b   .......

2.router-link-exact-active 精确匹配

to = '/my' 仅可以匹配 /my

<template>
  <div>
    <div class="footer_wrap">
      <router-link to="/find">发现音乐</router-link>
      <router-link to="/my">我的音乐</router-link>
      <router-link to="/friend">我的朋友</router-link>
    </div>
    <div>
      <router-view></router-view>
    </div>
  </div>
</template>
.footer_wrap a.router-link-active{
  background-color: aqua;
}

自定义匹配类名

const router = new VueRouter({
  // 路由规则
  routes:[
    {path:'/find',component:Find},
    {path:'/my',component:My},
    {path:'/friend',component:Friend}
  ],

  linkActiveClass:'active',
  linkExactActiveClass:'exact-avtive'

})
.footer_wrap a.active{
  background-color: aqua;
}

声明式导航-跳转传参

目标:在跳转路由时,进行传值

1.查询参数传参

语法格式如下

  • to = '/path?参数名 = 值'

对应页面组件接收传递过来的值

  • $route.query.参数名
<template>
  <div class="home">
    <router-link to="/search?key=百度">百度</router-link>
    <router-link to="/search?key=网易">网易</router-link>
    <router-link to="/search?key=腾讯">腾讯</router-link>
  </div>
</template>
<template>
  <div>
    <p>搜索关键字:{{ $route.query.key }}</p>
    <p></p>
  </div>
</template>

2.动态路由传参

1.配置动态路由

const router = new VueRouter({
  // 路由规则
  routes:[
    {path:'/search/:words',component:Search},
    {path:'/home',component:Home}
  ],

  linkActiveClass:'active',
  linkExactActiveClass:'exact-avtive'

})

2.配置导航链接

  • to="/path/参数值"
<template>
  <div class="home">
    <router-link to="/search/百度">百度</router-link>
    <router-link to="/search/网易">网易</router-link>
    <router-link to="/search/腾讯">腾讯</router-link>
  </div>
</template>

3.对应页面组件接收传递过来的值

  • $route.params.参数名
<template>
  <div>
    <p>搜索关键字:{{ $route.params.words }}</p>
    <p></p>
  </div>
</template>

Vue路由-重定向

问题:网页打开,url默认是/路径,未匹配到组件时,会出现空白

说明:重定向:匹配path后,强制跳转path路径

语法:

{path: 匹配路径,redirect:重定向到的路径}

const router = new VueRouter({
  // 路由规则
  routes:[
    {path:'/',redirect:'/home'},
    {path:'/search/:words',component:Search},
    {path:'/home',component:Home}
  ],

  linkActiveClass:'active',
  linkExactActiveClass:'exact-avtive'

})

Vue路由-404

作用:当路径找不到时,给个提示页面

位置:配在路由最后

语法:

{path:"*"(任意路径)-前面不匹配就命中最后这个}

const router = new VueRouter({
  // 路由规则
  routes:[
    {path:'/',redirect:'/home'},
    {path:'/search/:words',component:Search},
    {path:'/home',component:Home},
    {path:'*',component:NotFound}
  ],

  linkActiveClass:'active',
  linkExactActiveClass:'exact-avtive'

})

Vue路由-模式设置

问题:路由的路径看起来不自然,有#,能否切成真正的路径模式

  • hash路由(默认)例如:http://localhost:8080/#/home
  • history路由(常用)例如:http://localhost:8080/home(以后上线需要服务器端支持)
const router = new VueRouter({
    mode:'history',
  // 路由规则
  routes:[
    {path:'/',redirect:'/home'},
    {path:'/search/:words',component:Search},
    {path:'/home',component:Home},
    {path:'*',component:NotFound}
  ],

  linkActiveClass:'active',
  linkExactActiveClass:'exact-avtive'

})

历史记录在vue-router中的使用

历史记录在Vue Router中主要通过router对象来管理。具体来说,你可以使用this.$router来访问router对象。

要在Vue Router中使用历史记录,你可以通过以下方式进行操作:

编程式导航: 你可以使用this.$router.push()方法来向历史记录添加一个新的条目,或者使用this.$router.replace()方法来替换当前的历史记录条目。例如:

// 添加新的历史记录条目
this.$router.push('/new-route');

// 替换当前的历史记录条目
this.$router.replace('/new-route');

控制历史记录: 你可以使用this.$router.go()方法来在历史记录中前进或后退多少步,也可以使用this.$router.back()this.$router.forward()方法来执行后退或前进操作。

// 后退一步
this.$router.go(-1);

// 前进一步
this.$router.go(1);

监听历史记录变化: 你可以通过监听this.$router对象的事件来处理历史记录的变化。例如,你可以监听beforeEachbeforeResolveafterEach等事件来执行相应的操作。

this.$router.beforeEach((to, from, next) => {
  // 在导航触发之前执行的逻辑
});

this.$router.afterEach((to, from) => {
  // 导航完成后执行的逻辑
});

实现嵌套路由

// 父路由组件
const router = new VueRouter({
  routes: [
    { path: '/parent', component: ParentComponent, children: [
      { path: 'child', component: ChildComponent }
    ]}
  ]
});

命名视图

命名视图(Named Views)是 Vue Router 提供的一项功能,允许你在同一个页面中同时显示多个命名视图的内容。这在构建复杂的页面布局时非常有用,可以让不同的组件渲染到页面中不同的位置。

在 Vue Router 中使用命名视图,需要在路由配置中指定每个视图的名称,并在组件中使用 <router-view> 标签来显示对应名称的视图内容。

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: HomeComponent,
        header: HeaderComponent,
        sidebar: SidebarComponent
      }
    }
  ]
});

在上面的路由配置中,我们定义了三个命名视图:defaultheadersidebar,分别对应不同的组件。然后在页面模板中可以这样使用:

<div id="app">
  <router-view name="header"></router-view>
  <router-view></router-view> <!-- 默认会显示 default 视图 -->
  <router-view name="sidebar"></router-view>
</div>

导航守卫

导航守卫是 Vue Router 中用于控制路由跳转的功能,可以在路由导航过程中进行一些操作,比如权限验证、页面加载前后的处理等。导航守卫主要分为全局前置守卫、全局解析守卫、全局后置钩子和路由独享守卫。

1. 全局前置守卫(Global Before Guards)

  • beforeEach(to, from, next):在路由跳转之前调用,常用于进行权限验证或其他全局操作。

2. 全局解析守卫(Global Resolve Guards)

  • beforeResolve(to, from, next):在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后调用。

3. 全局后置钩子(Global After Hooks)

  • afterEach(to, from):在导航完成之后调用,常用于页面切换后的一些操作。

4. 路由独享守卫(Per-Route Guard)

  • beforeEnter(to, from, next):在单个路由配置中定义的守卫,在进入该路由前调用。
  • const router = new VueRouter({
      routes: [
        {
          path: '/home',
          component: HomeComponent,
          beforeEnter: (to, from, next) => {
            // 进入路由前的操作,如权限验证
            if (userAuthenticated) {
              next();
            } else {
              next('/login');
            }
          }
        }
      ]
    });
    
    router.beforeEach((to, from, next) => {
      // 全局前置守卫,可用于登录状态验证等
      next();
    });
    
    router.afterEach((to, from) => {
      // 全局后置钩子,在导航完成后调用
    });
    

    路由元信息

    路由元信息是 Vue Router 中一种特殊的字段,允许你在路由对象中添加额外的自定义信息,比如页面标题、权限要求、页面描述等。这些元信息可以在路由导航过程中访问,并根据需要进行处理。

    export default {
      mounted() {
        console.log(this.$route.meta.title); // 输出 'Home Page'
      }
    };
    

在路由组件中,你可以通过 this.$route.meta 来访问路由的元信息

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Home,
      meta: { requiresAuth: true, title: 'Home Page' }
    }
  ]
});

路由过渡动效

Vue Router 提供了过渡效果的功能,可以让页面在路由切换时产生动画效果,提升用户体验。你可以使用 Vue 的 <transition> 组件或 <transition-group> 组件来实现路由过渡动效。

使用 <transition> 组件:

<template>
  <transition name="fade" mode="out-in">
    <router-view></router-view>
  </transition>
</template>

<style>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

使用 <transition-group> 组件:

<template>
  <transition-group name="slide" mode="out-in">
    <router-view></router-view>
  </transition-group>
</template>

<style>
.slide-enter-active, .slide-leave-active {
  transition: transform 0.5s;
}
.slide-enter, .slide-leave-to {
  transform: translateX(100%);
}
</style>

  • 26
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue Router 是 Vue.js 官方提供的路由管理器。它允许你在 Vue.js 应用中实现单页面应用(SPA)的路由功能。通过使用 Vue Router,你可以定义不同的路由路径和对应的组件,使得在用户访问不同的路径时,能够动态地加载相应的组件内容,实现页面的切换。 Vue Router 提供了路由配置的方式,可以在路由配置中定义各个路径对应的组件,并且可以设置路由参数、路由守卫等。 在 Vue.js 应用中使用 Vue Router 需要先安装依赖包。你可以使用 npm 或 yarn 进行安装,命令如下: ```bash npm install vue-router # 或者 yarn add vue-router ``` 安装完成后,你需要在你的 Vue.js 应用中引入 Vue Router,并在 Vue 实例中使用它。你可以在入口文件(如 main.js)中进行配置,示例代码如下: ```javascript import Vue from 'vue' import VueRouter from 'vue-router' import Home from './components/Home.vue' import About from './components/About.vue' Vue.use(VueRouter) const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ] const router = new VueRouter({ routes }) new Vue({ router, render: h => h(App) }).$mount('#app') ``` 在上面的示例代码中,我们引入了两个组件 Home 和 About,并定义了两个路由路径 '/' 和 '/about' 对应的组件。然后创建了一个 VueRouter 实例,并传入了路由配置。最后,我们将创建的 router 实例传入到 Vue 实例中,使得整个应用具有路由功能。 这只是一个简单的示例,Vue Router 还提供了更多的配置选项和路由功能,比如嵌套路由、命名路由、动态路由等等。你可以查阅 Vue Router 的官方文档来获取更详细的信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值