Vue Router4路由

原文链接:https://blog.csdn.net/qq_41260655/article/details/119384770

1、Vue-router是什么?
Vue.js 的官方路由(就这么简单一句话)

2、Vue Router4 新特性
简单对比总结了一下

Vue3支持最新版本由于Vue 3 引入了createApp API,该API更改了将插件添加到Vue实例的方式。 因此,以前版本的Vue Router将与Vue3不兼容。Vue Router 4 引入了createRouter API,该API创建了一个可以在Vue3中安装 router 实例。
History选项在Vue Router 4中,这些模式已被抽象到模块中,可以将其导入并分配给新的history 选项。 这种额外的灵活性让我们可以根据需要自定义路由器。
// Vue Router 4
import { createRouter, createWebHistory } from "vue-router";
export default createRouter({
  history: createWebHistory(),
  routes: [],
});
 
动态路由Vue Router 4 提供了addRoute方法实现动态路由。这个方法平时比较少用到,但是确实有一些有趣的用例。 例如,假设我们要为文件系统应用程序创建UI,并且要动态添加路径。 我们可以按照以下方式进行操作:
methods: {
  uploadComplete (id) {
    router.addRoute({
      path: `/uploads/${id}`,
      name: `upload-${id}`,
      component: FileInfo
    });
  }
}
 
导航守卫可以返回值并非next导航守卫是Vue Router的钩子,允许用户在跳转之前或之后运行自定义逻辑,例如 beforeEach,beforeRouterEnter等。它们通常用于检查用户是否有权访问某个页面,验证动态路由参数或销毁侦听器。在版本4中,我们可以从hook 方法中中返回值或Promise。 这样可以方便快捷地进行如下操作:

// Vue Router 3
router.beforeEach((to, from, next) => {
  if (!isAuthenticated) {
    next(false);
  }
  else { 
    next();
  }
})
// Vue Router 4
router.beforeEach(() => isAuthenticated);
 
3、安装和配置router.js文件
npm install vue-router@4//一般使用npm,4.x的版本最新
1
import {
    createRouter,
    createWebHashHistory
} from 'vue-router'

import Server from "../components/distribution_services/Index.vue"
import Data from "../components/data_processing/Index.vue"
import Visual from "../components/three_dimensional_visualization/Index.vue"
import Details from "../components/authorization_details/index.vue"
import Buy from "../components/authorized_purchase/Index.vue"
import Terrain from "../components/distribution_services/terrain/Index.vue"
import Image from "../components/distribution_services/image/Index.vue"
import Lodmodel from "../components/distribution_services/lodModel/Index.vue"
import Resource from "../components/distribution_services/assets/Index.vue"
import Scene from "../components/distribution_services/scene/Index.vue"
import Tile from "../components/distribution_services/model/Index.vue"
import Tilt from "../components/distribution_services/osgb/Index.vue"

const router = createRouter({
    history: createWebHashHistory(), // hash模式:createWebHashHistory,history模式:createWebHistory
    //hash 模式使用URL哈希来模拟完整的URL,以便在URL更改时不会重新加载页面。 history 模式利用 HTML5 History API 来实现URL导航,也是无需重新加载页面。
    linkExactActiveClass: 'active',//配置高亮
    routes: [{
            path: '/',
            name: 'data',
            components: {
                out: Data
            }
        },
        {
            path: '/server',
            name: 'server',
            redirect: '/server/terrain', //首个重定向
            components: {
                out: Server
            },
            //路由嵌套使用children
            children: [{
                    path: 'terrain',
                    name: 'terrain',
                    components: {
                        inside: Terrain
                    },
                }, {
                    path: 'image',
                    name: 'image',
                    components: {
                        inside: Image
                    },
                },
                {
                    path: 'lodmodel',
                    name: 'lodmodel',
                    components: {
                        inside: Lodmodel
                    },
                },
                {
                    path: 'resource',
                    name: 'resource',
                    components: {
                        inside: Resource
                    },
                },
                {
                    path: 'scene',
                    name: 'scene',
                    components: {
                        inside: Scene
                    },
                },
                {
                    path: 'tile',
                    name: 'tile',
                    components: {
                        inside: Tile
                    },
                },
                {
                    path: 'tilt',
                    name: 'tilt',
                    components: {
                        inside: Tilt
                    },
                },
            ]
        },
        {
            path: '/visual',
            name: 'visual',
            components: {
                out: Visual
            }
        },
        {
            path: '/details',
            name: 'details',
            components: {
                out: Details
            }
        },
        {
            path: '/buy',
            name: 'buy',
            components: {
                out: Buy
            }
        }

    ]
})

export default router
 
以上是routerjs文件,在vue4中引入router

app.use(router)
1
高亮配置

通过router.js中 linkExactActiveClass: ‘active’,//配置高亮
然后在css中.router-link-active{background:#fff}即可
4、router-link和router-view
router-link 自定义组件,用来创建链接,可实现不重新加载页面的情况下更改URL地址,通过传入to 属性指定链接。
router-view 将显示与 url 对应的组件,相当于一个视图窗口
视图注意点:我们如果多个router-view的时候,怎么指定view视图窗口?


配置router.js文件中components中可以看到,属性名称是router-view的对应名称,自定义即可

5、路由嵌套


如你所见,children 配置只是另一个路由数组,就像 routes 本身一样。因此,你可以根据自己的需要,不断地嵌套视图。

6、编程式导航
这个更编程化思想一点,我个人用到link连接多一点

6.1导航不同位置
除了使用 <router-link> 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。

在 Vue 实例中,你可以通过 $router 访问路由实例。因此你可以调用 this.$router.push。

想要导航到不同的 URL,可以使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,会回到之前的 URL。

声明式    编程式
<router-link :to="...">    router.push(...)
该方法的参数可以是一个字符串路径,或者一个描述地址的对象。例如:

// 字符串路径
router.push('/users/eduardo')

// 带有路径的对象
router.push({ path: '/users/eduardo' })

// 命名的路由,并加上参数,让路由建立 url
router.push({ name: 'user', params: { username: 'eduardo' } })

// 带查询参数,结果是 /register?plan=private
router.push({ path: '/register', query: { plan: 'private' } })

// 带 hash,结果是 /about#team
router.push({ path: '/about', hash: '#team' })
 
注意:如果提供了 path,params 会被忽略,上述例子中的 query 并不属于这种情况。取而代之的是下面例子的做法,你需要提供路由的 name 或手写完整的带有参数的 path :

const username = 'eduardo'
// 我们可以手动建立 url,但我们必须自己处理编码
router.push(`/user/${username}`) // -> /user/eduardo
// 同样
router.push({ path: `/user/${username}` }) // -> /user/eduardo
// 如果可能的话,使用 `name` 和 `params` 从自动 URL 编码中获益
router.push({ name: 'user', params: { username } }) // -> /user/eduardo
// `params` 不能与 `path` 一起使用
router.push({ path: '/user', params: { username } }) // -> /user
 
由于属性 to 与 router.push 接受的对象种类相同,所以两者的规则完全相同。

6.2替换当前位置
它的作用类似于 router.push,唯一不同的是,它在导航时不会向 history 添加新记录,正如它的名字所暗示的那样——它取代了当前的条目。

声明式    编程式
<router-link :to="..." replace>    router.replace(...)
也可以直接在传递给 router.push 的 routeLocation 中增加一个属性 replace: true :

router.push({ path: '/home', replace: true })
// 相当于
router.replace({ path: '/home' })
 
6.3横跨历史
该方法采用一个整数作为参数,表示在历史堆栈中前进或后退多少步,类似于 window.history.go(n)。图下所示

// 向前移动一条记录,与 router.forward() 相同
router.go(1)

// 返回一条记录,与router.back() 相同
router.go(-1)

// 前进 3 条记录
router.go(3)

// 如果没有那么多记录,静默失败
router.go(-100)
router.go(100)
 
6.4篡改历史
router.push、router.replace 和 router.go 是 window.history.pushState、window.history.replaceState 和 window.history.go 的翻版,它们确实模仿了 window.history 的 API。
因此,在使用 Vue Router 时,操作历史记录就会觉得很熟悉。

7、重定向
7.1重定向得使用场景
首先学习和使用一项技术要知道为什么要用?应用场景是什么?在官网中并没有直接解释说明,只是上来告诉如何去用

下边看例子

以上两图得区别是什么?当我点击一级路由时会显示二级目录,但是这个时候我想默认选中/重定向一个二级路由,这时候怎么办?当我点击一级路由时候,这个时候重定向二级路由中一个,当成默认选项

7.2如何设置重定向?


重定向也是通过 routes 配置来完成,下面例子是从 /a 重定向到 /b:
const routes = [{ path: '/home', redirect: '/' }]
1
重定向的目标也可以是一个命名的路由:
const routes = [{ path: '/home', redirect: { name: 'homepage' } }]
1
甚至是一个方法,动态返回重定向目标:
const routes = [
  {
    // /search/screens -> /search?q=screens
    path: '/search/:searchText',
    redirect: to => {
      // 方法接收目标路由作为参数
      // return 重定向的字符串路径/路径对象
      return { path: '/search', query: { q: to.params.searchText } }
    },
  },
  {
    path: '/search',
    // ...
  },
]
 
8、导航守卫
导航守卫,顾名思义就是用户在跳转之前或之后运行自定义逻辑来实现一定的目的.

应用场景当没有登录的时候导航跳转的时候,重定向到login路由中(登录和内容区域是同一个页面)

// to代表将要访问的路径
// from代表从哪个路径跳转过来
// next是函数,表示放行
router.beforeEach((to,from,next) => {
  if(to.path === '/login') return next();
  const tokenStr = window.sessionStorage.getItem('token');//获取token值
  if(!tokenStr) return next('/login');
  next()
})
 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值