vue-router入门基础

vue-router和vuex是官方提供的Vue插件,主要解决路由和状态管理两个问题

vue-router

基本概念
解决什么问题?vue-router解决了路由与组件的对应关系

  1. vue-router的基本使用方法
npm i -S vue-router
cnpm i -S vue-router
  1. 使用vue-router插件
import Route from 'vue-router'
import A from './components/A.vue'
import B from './components/B.vue'
Vue.use(Route)

注:下述代码是用于关闭调试窗口重不重要描述

Vue.config.productionTip = false
  1. 初始化vue-router对象
const routes = [
  { path: '/a', component: A },
  { path: '/b', component: B },
  { path: '/hello-world', component: HelloWorld }
]
const router = new Route({
  routes
})
  1. 实例化Vue对象,传入router参数
new Vue({
  router,
  render: h => h(App)
})
  1. .使用router-view和router-link

router-view和router-link是vue-router官方提供的两个组件,router-view会替换为路由对应的组件,router-link相当于a标签,点击后会加载to属性中路由对应的组件

<div>
  <div>
    <router-link to="/a">a</router-link>
  </div>
  <div>
    <router-link to="/b">b</router-link>
  </div>
  <div>
    <router-link to="/hello-world">hello-world</router-link>
  </div>
</div>
<router-view />

路由嵌套

实现/a/aa路由,并且/aa对应的组件嵌套在/a之下,这时我们需要修改路由的配置文件:

const routes = [{
  path: '/a',
  component: A,
  redirect: '/a/aa',
  children: [
    { 
      path: '/a/aa',
      component: AA,
    }] 
}]

并修改A组件的内容:

<template>
  <div>
    <div>a</div>
    <router-view />
  </div>
</template>

由于A组件是父级路由,所以也需要添加router-view组件,动态匹配子路由

重定向

将一个路由重定向到另一个路由,实际开发过程中非常实用,修改配置文件即可:

const routes = [{
    path: '/a',
    component: A,
    redirect: '/a/aa',
    children: [{
      path: '/a/aa',
      component: AA,
    }] 
  }]

动态路由

为了支持restful形式路由以及更复杂的场景时,我们可以使用动态路由,定义路由时,在路由前加上冒号即可,我们先添加AA2组件,动态路由部分通过this.$route.params进行接收:

<template>
  <div>
    aa2
    <div>{{id}}</div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        id: null
      }
    },
    created() {
      this.id = this.$route.params.id
    }
  }
</script>

修改路由配置后生效:

const routes = [
  {
    path: '/a',
    component: A,
    redirect: '/a/aa',
    children: [
      {
        path: '/a/aa',
        component: AA,
      },
      {
        path: '/a/:id',
        component: AA2,
      },
    ]
  }
]

动态路由的优先级低于普通路由,所以我们访问/a/aa时会匹配到AA组件,而输入其他路由时会匹配到AA2组件

路由参数

参数传递是我们开发过程中必不可少的步骤,vue-router支持参数传递,通过this.$route.query进行接收,我们修改AA组件进行测试。

<template>
  <div>
    aa
    <div>{{message}}</div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        message: ''
      }
    },
    created() {
      this.message = this.$route.query.message || ''
    }
  }
</script>

编程式路由

有很多时候我们需要手动操作路由的跳转,这时我们需要使用this.$router,以下是一些常用的操作:

  • 路由跳转
this.$router.push('/a/aa')
  • 带参数路由跳转
this.$router.push({
 path: '/a/aa',
 query: {
   message: 'hello'
 }
})
  • 不向history插入记录
this.$router.replace('/a/123')
  • 回退
this.$router.go(-1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值