Vue路由的使用——定义、传参

路由,其实就是指向的意思。例如当我点击页面上的home按钮时,页面中就要显示home的内容,如果点击页面上的about 按钮,页面中就要显示about 的内容。点击之后,怎么做到正确的对应,比如,我点击home 按钮,页面中怎么就正好能显示home的内容——这就要在js 文件中配置路由。

在Web开发中,路由是指根据URL分配到对应的处理程序。对于大多数单页面应用,都推荐使用官方支持的vue-router。Vue-router通过管理URL,实现URL和组件的对应,以及通过URL进行组件之间的切换。

路由的基本概念

1、route
route它是一条路由,例如 Home按钮 => home是一条route, about按钮 => about 也是一条路由。单个路由定义形式如下:

{ 
	//路由路径
	path: '/foo', 
	//路由自定义名称
	name:'Foo',
	//路由跳转到的组件
	component: Foo 
	}

2、routes
routes是一组路由,单个的路由组合起来,形成一个数组。routes的形式如下:

routes:[
	route1,
	route2
	]

客户端中的路由,实际上就是dom 元素的显示和隐藏。

路由的使用

一、安装vue-router

npm install vue-router

二、配置路由

1、在src/router/index.js中配置路由。

import Vue from 'vue'
import VueRouter from 'vue-router'  //导入路由模块
import HelloWorld from '@/components/HelloWorld'   //导入路由用到的组件
import Home from '@/components/Home'
import About from '@/components/About'
//全局使用路由模块
Vue.use(VueRouter)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/home',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      component: About
    }
  ]
})

路由重定向

当路由定义中有两条路径指向同一个组件时,就需要重定向。所谓重定向,就是重新给它指定一个方向。假如,它本来是访问 ‘/’ 路径,我们重新指向‘/home’,它就相当于访问 ‘/home’,相应地,home组件就会显示到页面上。VueRouter中用 redirect 来定义重定向。
例如:

export default new Router({
  routes: [
    {
      path: '/home',
      name: 'home',
      component: Home
    },
    {
      path: '/',
      redirect:'/home'
    }
  ]
})

用重定向和单独配置路由的区别:

● 重定向实际上是当匹配到路径符合条件的时候去执行对应的路由,当然这个时候的url上面的地址显示的是对应的路由(url发生变化),页面也是对应的路由页面;

● 重新配置路由是当匹配到路径符合条件的时候,router-view页面展示部分负责拿符合条件路由的页面来展示,实际上url是没有发生变化的

2、在main.js中把路由注入到根实例中

import router from './router/index.js'  //import router 的router 一定要小写, 不要写成Router, 否则报 can't match的报错

new Vue({
  el: '#app',
  router,    // 将路由注入到根实例中,让整个应用都有路由功能
  components: { App },
  template: '<App/>'
})

三、使用路由

1、创建路由链接和路由视图

① 路由链接:<router-link to="/...">...</router-link>

< router-link> 标签将会渲染成 a 标签,to 属性变成了a 标签的 href 属性,也就是点击跳转的意思。(用< router-link> 标签来代替< a>标签)

② 路由视图:<router-view></router-view>

< router-view> 标签将会渲染成我们定义的路由组件,其实它就是一个占位符。它出现什么地方,路由路径匹配的组件就出现什么地方;它出现几次,路由路径匹配的组件就出现几次。

App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <center>
      <router-link to="/home">Home</router-link>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <router-link to="/about">About</router-link>
    </center>
	<router-view></router-view>
    <router-view></router-view>  //重复两次路由视图
  </div>
</template>

结果如下
在这里插入图片描述可以发现:
● < router-link> 标签渲染成了 a 标签,to 属性变成了a 标签的 href 属性,也就是点击跳转的意思。
● < router-view>< /router-view>标签出现两次,路由匹配的组件就出现两次。
● 当点击Home和About 来回切换时,a 标签有一个样式类 .router-link-active 也在来回切换,这是当router-link 处于选中状态时,vueRouter 会自动添加这个类。

2、点击路由跳转

使用@click绑定点击事件,在方法中使用this.$router.push({ path:'/home' })跳转指定组件

<template>
	<input type="button" @click="toHome">Home</input>
</template>

<script>
	export default{
		methods:{
			toHome(){
				this.$router.push({
                    path:'/home',
                		})
                	}
                }
			}
</script>

四、路由传递和获取参数

传递参数有两种方法:声明式 <router-link>和编程式$ router.push.

1、声明式 <router-link>

(1)方式一:传统url后拼接

①父组件App.vue中传递参数:使用< router-link to="/需要跳转的路由路径/需要传递的参数">< /router-link>标签进行导航。

<router-link to="/home/123">Home</router-link>

②子组件Home.vue中接收参数:在mounted中使用this.$route.params.num来接收路由参数。

<template>
  <div>
    <h1>{{ userId }}</h1> 
  </div>
</template>
 
<script>
export default {
  name: 'home',
  data () {
    return {
     userId: ''
    }
  },
  mounted(){
    this.userId = this.$route.params.userId
    }
  }
}
</script>
 
<style>
</style>

③路由配置文件index.js中:

{
      path: '/home/:userId',
      name: 'home',
      component: Home
    },

(2)方式二:命名路由(name+params)

①父组件传递参数

//这里的name指的是路由配置文件中的路由名称
<router-link :to="{ name: 'home', params: { userId: 123}}">click to news page</router-link>

②子组件接收参数:在mounted中使用this.$route.params.num来接收路由参数。

<template>
  <div>
    <h1>{{ userId }}</h1> 
  </div>
</template>
 
<script>
export default {
  name: 'home',
  data () {
    return {
     userId: ''
    }
  },
  mounted(){
    this.userId = this.$route.params.userId    //获取参数
    }
  }
}
</script>
 
<style>
</style>

获取参数也可以直接写为

<template>
  <div>
    <h1>{{ this.$route.params.userId }}</h1> 
  </div>
</template>

③配置文件

{
      path: '/home',
      name: 'home',  //与传递参数的name相一致
      component: Home
    },

(3)方式三:查询参数(path+query)

①父组件传递参数

//这里的path指的是路由配置文件中的路由路径
<router-link :to="{ path: '/home', query: { userId: 123}}">click to news page</router-link>

②子组件接收参数:在mounted中使用this.$route.params.num来接收路由参数。

<template>
  <div>
    <h1>{{ userId }}</h1> 
  </div>
</template>
 
<script>
export default {
  name: 'home',
  data () {
    return {
     userId: ''
    }
  },
  mounted(){
    this.userId = this.$route.query.userId   //获取参数
    }
  }
}
</script>
 
<style>
</style>

获取参数也可以直接写为

<template>
  <div>
    <h1>{{ this.$route.query.userId }}</h1> 
  </div>
</template>

③配置文件

{
      path: '/home',  //与传递参数的path相一致
      name: 'home',  
      component: Home
    },

2、编程式$ router.push

(1)方式一:传统url后拼接

①父组件App.vue中传递参数

<template>
  <div >
    //绑定事件
    <input type="button" @click="routerTo(111)">click here to news page</button>
  </div>
</template>
 
<script>
export default {
  name: 'App',
  methods:{
    routerTo(userId){
      this.$router.push({ path:'/home/${userId}'});
    }
  }
}
</script>
 
<style>
</style>

②子组件Home.vue接收参数

<template>
  <div>
    this is the news page.the transform param is {{this.$route.params.userId}}
  </div>
</template>
<script>
  
</script>

③配置文件index.js

{
      path: '/home/:userId',  
      name: 'home',  
      component: Home
    },

(2)方式二:命名路由

①父组件App.vue中传递参数

<template>
  <div >
    //绑定事件
    <input type="button" @click="routerTo">click here to news page</button>
  </div>
</template>
 
<script>
export default {
  name: 'App',
  methods:{
    routerTo(){
      this.$router.push({ 
      name: 'home', 
      params: { 
      userId: 123 
      }
      });
    }
  }
}
</script>
 
<style>
</style>

②子组件Home.vue接收参数

<template>
  <div>
    this is the news page.the transform param is {{this.$route.params.userId}}
  </div>
</template>
<script>
  
</script>

③配置文件index.js

{
      path: '/home',  //与传递参数的path相一致
      name: 'home',  
      component: Home
    },

(3)方式三:查询参数

①父组件App.vue中传递参数

<template>
  <div >
    //绑定事件
    <input type="button" @click="routerTo">click here to news page</button>
  </div>
</template>
 
<script>
export default {
  name: 'App',
  methods:{
    routerTo(){
      this.$router.push({ path: '/home', query: { userId: 123 }});
    }
  }
}
</script>
 
<style>
</style>

②子组件Home.vue接收参数

<template>
  <div>
    this is the news page.the transform param is {{this.$route.params.userId}}
  </div>
</template>
<script>
  
</script>

③配置文件index.js

{
      path: '/home',  //与传递参数的path相一致
      name: 'home',  
      component: Home
    },

(1)推荐是name和params搭配,path和query搭配。不可以在<
router-link>的路由对象中同时出现path和params,此时params作废,目的页面中获取不到参数。
(2)使用params传递参数时,参数不会拼接在url后面;使用params传递参数时,参数会拼接在url后面。
(3)最好用query的形式传递参数以及获取参数而不用params:因为采用params的方式传递参数,当你进入到目的页面后确实能够正确地获取参数,但是,当你刷新页面时,参数就会丢失;而以query形式传递参数刷新页面时不会丢失。

五、嵌套路由

嵌套路由,是由我们的页面结构所决定的。当我们进入到Home页面的时候,它下面还有分类,如手机系列,平板系列,电脑系列。当我们点击各个分类的时候,它还是需要路由到各个部分,如点击手机,它肯定到对应到手机的部分。

在路由的设计上,首先进入到 home ,然后才能进入到phone、 tablet、 computer 。Phone、tablet、compute 就相当于Home的子元素。所以Vue 提供了childrens 属性,它也是一组路由,相当于我们所写的routes。

Vue组件页面:

<template>
    <div>
        <h1>home</h1>
        <p>
        	//路由是先进入到Home,然后才进入相应的子路由如 phone,所以书写时要把 home 带上 
            <router-link to="/Home/phone">手机</router-link>
            <router-link to="/Home/tablet">平板</router-link>
            <router-link to="/Home/computer">电脑</router-link>
        </p>
        <router-view></router-view>
    </div>
</template>

路由配置如下:

	{
        path:"/home",
     // 下面这个属性不可少,因为我们先进入home页面,才能进入子路由
        component: home,
     // 子路由
        children: [
        // 当进入到home时,下面的组件显示
    		{
        		path: "",
        		component: phone
    		},
            {
                path: "phone",
                component: phone
            },
            {
                path: "tablet",
                component: tablet
            },
            {
                path: "computer",
                component: computer
            }
        ]
    }

注意:在children中,必须先定义{ path: "",component: phone}。因为当我们点击Home 时,应该没有任何对应的组件进行显示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值