Vue router

阅读数:103 评论数:0

跳转到新版页面

分类

html/css/js

正文

一、基本使用

如果在一个模块化工程中使用它, 必须要通过Vue.use()明确地安装路由功能.

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        {
          // 当 /user/:id/profile 匹配成功,
          // UserProfile 会被渲染在 User 的 <router-view> 中
          path: 'profile',
          component: UserProfile
        },
        {
          // 当 /user/:id/posts 匹配成功
          // UserPosts 会被渲染在 User 的 <router-view> 中
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})

二、编程式导航

当使用 <router-link> 时,内部会调用router.push(...)这个方法,所以点击 <router-link :to="..."> 相当于调用 router.push(...)

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

(1) router.push(location, onComplete?, onAbort?)

(2) router.replace(location, onComplete?, onAbort?)

跟router.push很像, 唯一的不同就是, 它不会向history添加新记录.

(3) router.go(n)

在history记录中向前或者向后退多少步.

三、命名路由

在创建Router实例的时候, 在routes配置中给某个路由设置名称.

const router = new VueRouter({
  routes: [
    {
      path: '/user/:userId',
      name: 'user',
      component: User
    }
  ]
})

四、命名视图

有时想同时展示多个视图, 例如创建一个布局, 有sidebar和main两个视图, 这个时候命名视图就派上用场了.你可以在界面中拥有多个单独命名的视图, 而不只有一个单独的出口. 如果router-view没有设置名字, 那么默认为default.

<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
 
const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    }
  ]
})

https://router.vuejs.org/zh/guide/

五、历史模式和哈希模式

前端路由的核心,就在于改变视图的同时不会向后端发出请求。

1、hash模式

hash模式是把前端路由的路径用井号#拼接在真实url后面的模式,当井号后面的路径发生变化时,只会触发onhashchange事件。

(1)hash可以改变url,但是不会触发页面重新加载,即不会刷新页面。这样模式不利于于SEO优化。

(2)仅hash符号之前的内容会被包含在请求中,因此对于后端来说,即使没有做到对路由的全覆盖,也不会返回404错误 。

2、history模式

利用了H5的接口:pushState()和replaceState()方法。

(1)会出现404的情况,需要后台配置。

六、钩子函数

1、全局钩子

每次跳转路由时都会执行这个钩子函数,由router调用

to:到哪个路由去

from:从哪个路由来

next:判断是否进入

(1)beforeEach(to,from,next)

页面加载之前执行,有三个参数

router.beforeEach((to, from, next) => {
  if (to.matched.length === 0) {
    from.name ? next({ name : from.name }) : next('/')
  } else {
    next()
  }
})

next有几种形式:next()可以跳转到目标路由;next(false)不可跳转,回到源路由;next(/path)中断当前跳转路径,跳转到path指定的路由;next(error)当前跳转终止,并执行router.onError中的回调函数

router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {
        //判断该路由是否需要登录权限
        if (cookies('token')) {
            //通过封装好的cookies读取token,如果存在,name接下一步如果不存在,那跳转回登录页
            next()//不要在next里面加"path:/",会陷入死循环
        }
        else {
            next({
                path: '/login',
                query: {redirect: to.fullPath}//将跳转的路由path作为参数,登录成功后跳转到该路由
            })
        }
    }
    else {
        next()
    }
})

(2)afterEach(to,from)

页面加载之后执行,有两个参数,没有next

router.afterEach((to,from) => {
  console.log(to);//到达的路由
  console.log(from);//离开的路由
})

2、单个路由钩子

只要用于指定某个特定路由跳转时的逻辑,写在某个路由配置内部

(1)beforeEnter()

(2)beforeLeave()

const routes = [
    {
        path: '/home',
        component: Home
        
        beforeEnter;(to,from,next) => {
            console.log(to)
        }
 
        beforeLeave:(to,from,next) => {
            console.log(from)
        }
    }

3、组件内部钩子

在组件内使用

(1)beforeRouterEnter()

(2)beforeRouterLeave()

(3)beforeRouterUpdate() 下一次更新之前

const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当钩子执行前,组件实例还没被创建
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
 
  }

 




相关推荐

1、query要用path来引入,接收参数都是this.$route.query.name。query类似于ajax中get传参,即在浏览器地址栏中显示参数。<

一、使用pnpm新建项目 可以使用npm 或yarn或pnpm来初始化Vite项目 pnpm create vite xxx(项目名称) #选择vue #选择js cd xxx (进入项目目录) #安

缓存页面主要Jul为了防止重复渲染dom,减少加载时间及性能消耗,提高用户体验。 一、旧版的语法 <keep-alive> <router-view v-if="$route.meta.kee

一、动态路由 vue3必须使用vue-router4,而router4去掉了addRoutes,只能使用addRoute 二、不匹配url跳转到404 1、首先,你需要一个 404 组件,这个组件将会