vue-router知识点整理(一)

274 阅读1分钟

vue-router与vue深度结合

作用:将vue的组件映射到(路由)routes中,然后告诉vue-router,对应的组件在什么路由下进行渲染

导入vue

import Vue from 'vue'
import VueRouter from 'vue-router'

注册成vue的组件

Vue.use(VueRouter)

实例化vue-router

import Index from 'Index.vue' // 组件导入
const routes = [
    {
        path: '/',
        name: 'index',
        component: Index  // 挂载对应路由要展示的组件
    }
]; // 定义路由列表
const router = new VueRouter({
    routes
})

创建和挂载根实例上

const app = new Vue({
    router
}).$mount('#app')

动态路由匹配

通过在配置path的路径中用 :来区分

// 路由配置
routes = [
    {
       path: '/user/:name/post/:id',
       name: 'user',
       component: User
    }
]
// 声明式访问方式
<router-link to="/user/zhangsan/post/123"></router-link>
// 编程式访问方式
this.$router.push({
    // path: '/user/zhangsan/post/123'(如果是使用的path访问,那么params将会失效)
    name: 'user',
    params: {
        name: 'zhangsan',
        id: 123
    }
})

// 页面获取方式
this.$route.params

// 匹配所有路由 通过 * 号匹配 
routes = [
    {path: '/user*', ...}
]
所有/user开头的路由都会跳到这个组件

路由嵌套

在当前路由下添加children[] 这里面的配置与同级配置相同

routes = [
    {
       path: '/layout',
       name: 'parent',
       component: parent,
       children: [
           {path: 'one', name: 'one', component: one,},
           {path: 'two', name: 'two', component: two,}
       ]
    }
];
// 在同一个页面访问二级路由
<router-link to="/layout/one">one</router-link>
<router-link to="/layout/two">two</router-link>
<router-view/> 用来展示路由的视图

命名视图

在同一级路由页面展示多个视图,而不是嵌套,可以用在配置布局组件时

// 组件中给router-view添加name
<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>
// 路由配置中使用components给对应的name添加上组件即可
routes = [
    {
        path: '/',
        components: {
            a: 组件A,
            b: 组件B
        }
    }
]

路由组件传参

开启props可以将route与组件参数解耦,组件可以单独使用

// user组件
<template>
  <div>
      <p>路由{{ $route.params }}</p>
      <p>组件props{{id }} --- {{ name }} ??? {{ value }}</p>
  </div>
</template>
<script>
export default {
  name: "routecomponent",
  props: ["id", "name", "value"]
}
</script>

// 路由配置
// 1作为布尔值 会将动态路由的参数作为组件props的值
// 2作为对象,可以将对象中的值作为props的值
routes = [
     {
    path: '/routecomponent/:name/:id',
    name: 'routecomponent',
    props: true,
    component: User
  }
]

History和hash的区别

1.hash的url带有#号,history没有。

2.hash模式下,浏览器向服务端发送请求时,只会把#前的链接发送给服务端,所以后端同学并不需要处理,并且页面可以刷新不会返回404之类的页面。