vue-router的笔记

路由:hash地址与组件之间的对应关系

SPA:单页面应用程序

前端路由的工作方式

1、用户点击了页面上的路由链接

2、导致了url地址栏的hash值变化

3、前端路由监听到了hash地址的变化

4、前端路由把当前hash地址对应的组件渲染到浏览器中

在vue项目中,要想把路由用起来,必须把路由实例对象,通过以下方式挂载

import router from '@/router/index.js'
new Vue({
render: h => h(App),
router: router
}).$mount('#app')

只要在项目中安装vue-router 就可以使用

    <router-view></router-view>

作用:占位符

在index.js中配置导入变换的组件

import Movie from '@/components/Movie.vue'
import Home from '@/components/Home.vue'
import About from '@/components/About.vue'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
  { path: '/Home', component: Home },
  { path: '/About', component: About },
  { path: '/Movie', component: Movie }
]
})

使用 router -link替代a链接

    <router-link to="/Home">首页</router-link>
  <router-link to="/Movie">电影</router-link>
  <router-link to="/About">关于</router-link>

路由重定向:用户在访问地址A的时候,强制用户跳转到地址C,从而展示特定的组件页面,通过路由规则的redirect属性,指定一个新的路由地址,可以很方便地设置路由的重定向。

 { path: '/', redirect: '/Home' },

嵌套路由

{
    path: '/About',
    component: About,
    children: [
      { path: 'Tab1', component: Tab1 },
      { path: 'Tab2', component: Tab2 }
    ]
  },

默认子路由:如果children数组中,某个路由规则的path值为空字符串,则这条路由规则为默认子路由

{ path: '', component: Tab1 },

动态路由匹配

{ path: '/Movie/:id', component: Movie }

this.$route 是路由的参数对象

this.$router 是路由的导航对象

可以在组件中使用props接收动态路由的参数

{ path: '/Movie/:id', component: Movie, props: true }
props: ['id'],

在哈希地址中,斜线后面的参数项:叫做路劲参数,在路由参数对象中,需要使用this.$route.params拿到

在哈希地址中,?后面的参数叫做查询参数

在路由参数对象中,需要使用this.$route.query来访问查询参数

在this.$route中,pass只是路径地址,fullpath是完整的哈希地址

声明式导航&编程式导航

this.$router.push('hash地址')

跳转到指定hash地址,并增加一条历史记录

this.$router.replace("hash地址")

跳转到指定hash地址,并替换掉当前历史记录

this.$router.go(数值n)

可以在浏览器历史中前进和后退,如果只前进或后退一层

可以使用:$router.back() 或者 $router.forward()

(注意:使用编程式导航不能使用this)

导航守卫

全局前置守卫:在router 后面声明

const router = new VueRouter({
routes: [
  { path: '/', redirect: '/Home' },
  { path: '/Home', component: Home },
  {
    path: '/About',
    component: About,

    children: [
      { path: '', component: Tab1 },
      { path: 'Tab2', component: Tab2 }
    ]
  },
  { path: '/Movie/:id', component: Movie, props: true }
]
})
router.beforeEach((to, from, next) => {
//next表示放行
next()
})

next函数的三种调用方式

使用next('/login')可以让页面强制跳转到登录页面

next(false)当用户没有后台访问权限,不允许跳转到后台主页

posted @ 2023-03-07 23:31  guorunbin  阅读(24)  评论(0编辑  收藏  举报