安装

如果你的脚手架尚未安装vue-router请使用以下代码进行安装:
npm install vue-router --save
低版本:
npm install vue-router@3.5.1 --save-dev

为router单独创立一个文件便于管理

建议在src文件夹下创建"router"文件夹,然后在router文件夹下创建index.js 这个index.js就是我们的路由文件了
在这里插入图片描述
然后在index.js中引入 vue-router 并使用

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

这里防止跳转相同路径时报错做一下处理 现在不能理解的话 反正先写上去

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

然后引入需要跳转的组件举例:这里需要跳转到hello组件
1.引入hello 组件:

import hello from 'components/hello.vue'

2、配置它的路由:

export default new Router({
	routes: [
	    {
			path: '/',   //这里配置的是根目录也就是主页 该组件同样需要引入
			components: {
				default: index
			}
		}
		{
			path: '/hello',
			components: {
				default: hello
			}
		}
	]
})

同样的 跳转其他组件 也只需要 引入该组件 然后 做一下配置 整个文件看起来就是:
在这里插入图片描述

引入

在main.js中:

import Vue from 'vue'
import App from './App.vue'
import router from './router'

new Vue({
	router,//挂载router
    render: h => h(App)
}).$mount('#app')

这里vue-router就已经配置完成以及挂载完毕可以去使用了

使用

首先要注意:通过router跳转过去的组件 其组件的内容只会在< router-view ></ router-view >这个标签中显示,所以这里 我们配置一下App.vue:

<template>
  <div id="app">
   <router-view></router-view>
  </div>
</template>
<script>

export default {
  name: 'App',
  data(){
	  return{
		 
	  }
  },
  methods:{
  }
}
</script>

注意:因为我们配置了主页"index" 所以vue初始化会自动跳转到index组件中去
好了现在 我们需要在主页(index)中写一个按钮然后通过点击这个按钮跳转到hello组件中去
在index.vue中:
在这里插入图片描述
这样就已经实现跳转了 同样的 在hello组件中跳转到主页:
在这里插入图片描述

这里呢需要注意的是 跳转有两种方式 一种就是最直接的:
To Hello这种也是可以跳转的 另外一种就是我用的这种通过点击事件然后使用$router.push的方式 其他的区别先不说,有个区别就是使用第一种的话 页面会生成一个标签这让页面排版又复杂了一些 而且 不便于管理所以 我还是推荐第一种

传参

传参的话也很简单:

this.$router.push({name:'son',params:{from:'father'}})

或者

this.$router.push({path:'/father',query:{from:'son'}})

接收参数:

mounted(){
            console.log(this.$route.params);
        }

以及

mounted(){
            console.log(this.$route.query);
        }

两种方式的区别前者类似 post请求 大致上就是 前者地址栏不会暴露参数 而后者会 传参 取参的时候 是params还是query也需要对应上 感兴趣的可以去这里看一下:路由中的query 和 params的传参方式区别和详解

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐