Vue-Router的使用


Vue-Router 的使用

  • 在 vue2 项目中,选择使用 vue-router
  • 项目目录中会有 router 文件夹,/router/index.js 中配置路由

避免因路由重复报错

import Vue from 'vue'
import Router from 'vue-router'
const originalPush = Router.prototype.push

Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)

路由配置

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/pages/Home'
import MapTest from '@/pages/Map'
import One from '@/pages/one'

const originalPush = Router.prototype.push

Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      children:[
        {
          path: '/map',
          name: 'MapTest',
          component: MapTest
        },
        {
          path: '/one',
          name: 'One',
          component: One
        }
      ]
    }
  ]
})

路由跳转

router-link路由跳转

2.使用$router.push 路由跳转

this.$router.push({ name: '需要跳转的路由name'});

加载/map 路由下的默认组件

this.$router.push({ path: '/map' })

3.路由跳转传参

使用 name 跳转,使用 params 传参

this.$router.push({ name: '路由name', params: { search: value } })

获取路由参数

this.$route.params.search

使用 name 跳转,使用 query 传参

此方法传递参数,参数会出现在 url 地址中

this.$router.push({name:'路由name',query:{search:value}})

获取路由参数

this.$route.query.search

使用 path 跳转,在 url 中拼接参数

路由配置

{   
 path: 'myadmexp/details/:id'
}

路由跳转传参

this.$router.push({ path: '路由url'+id})

获取路由参数

this.$route.params.id

4.使用 router-view 展示路由对应组件