vue构建小项目-vue-router(二)

简介vue-router

首先,先看一下默认项目中的路由结构

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    // 动态路径参数 以冒号开头
    { path: '/user/:id', component: User }
  ]
})

这是router目录下的index.js,用来配置路由规则和路径。最后输出挂在到main.js
中创建vue实例上。上述例子就是一个动态路由的配置,组件和path做为关联。看一下官方的解释:
我们经常需要把某种模式匹配到的所有路由,全都映射到同个组件。例如,我们有一个 User 组件,对于所有 ID 各不相同的用户,都要使用这个组件来渲染。现在呢,像 /user/foo 和 /user/bar 都将映射到相同的路由。
path路径后面带有参数,:id也可以是?id这种形式。this.$route.params可以接受的值。这就涉及到路由传值,下面会详细介绍路由传值的各种方式。

var router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/login',
      name: 'login',
      component: login
    },
    {
      path: '/index',
      name: 'index',
      component: index
    },
    {
      path: '/detail?:id',//路由方式传值
      name: 'detail',
      component: detail
    }
  ]
})

配置的小项目中的路由。路由中如何跳转和使用呢?

//和后台请求balabala一大堆操作,成功执行下面操作就可以跳转到index页面。
this.$router.replace({ path: "/index" });
其他的跳转用法和区别:
this.$router.push()---跳转到不同的url,但这个方法回向history栈添加一个记录,点击后退会返回到上一个页面。
this.$router.replace()---同样是跳转到指定的url,但是这个方法不会向history里面添加新的记录,点击返回,会跳转到上上一个页面。上一个记录是不存在的。
this.$router.go(n)---相对于当前页面向前或向后跳转多少个页面,类似 window.history.go(n)。n可为正数可为负数。正数返回上一个页面

路由传值的三种方式


getDescribe(id) {
// 直接调用$router.push 实现携带参数的跳转
        this.$router.push({
          path: `/describe/${id}`,
        })

// 方案一,需要对应路由配置如下:
   {
     path: '/describe/:id',
     name: 'Describe',
     component: Describe
   }
// 很显然,需要在path中添加/:id来对应 $router.push 中path携带的参数。

// 在子组件中可以使用来获取传递的参数值。
$route.params.id
// 父组件中:通过路由属性中的name来确定匹配的路由,通过params来传递参数。
       this.$router.push({
          name: 'Describe',
          params: {
            id: id
          }
        })

// 对应路由配置: 注意这里不能使用:/id来传递参数了,因为父组件中,已经使用params来携带参数了。
   {
     path: '/describe',
     name: 'Describe',
     component: Describe
   }

//子组件中: 这样来获取参数
$route.params.id
[![复制代码](https://upload-images.jianshu.io/upload_images/19485757-c8570d17be5304de.gif?imageMogr2/auto-orient/strip)](javascript:void(0); "复制代码") 

// 父组件:使用path来匹配路由,然后通过query来传递参数
这种情况下 query传递的参数会显示在url后面?id=? this.$router.push({
          path: '/describe',
          query: {
            id: id
          }
        }) // 对应路由配置:
 {
     path: '/describe',
     name: 'Describe',
     component: Describe
   } // 对应子组件: 这样来获取参数
$route.query.id // 这里要特别注意 在子组件中 获取参数的时候是$route.params 而不是
$router 这很重要~~~
参考:https://www.cnblogs.com/EnSnail/p/8458001.html

你可能感兴趣的:(vue构建小项目-vue-router(二))