Vue2路由问题汇总

一:在main.js文件里配置了路由,可是页面不生效问题

1.没有设置路由的入口,需要在app.vue里设置路由的入口router-view
<template>
  <div id="app" class="container">
     <router-view v-wechat-title="$route.meta.title"></router-view>
  </div>
</template>

二:动态路由匹配的问题

1.注意一下vue2与vue1动态路由匹配的写法区别
//vue2动态路由匹配的写法区别
	const routes =[
		{
		    path: '/goods',
			component: goods
		},
		{
			path: '/ratings',
			component: ratings
		},
		{
			path: '/seller',
			component: seller
		}

	];
	const router = new VueRouter({
	  	routes
	});
	new Vue({
	  el: '#app',
	  router,
	  render: h => h(App)
	});

	//vue1动态路由匹配的写法区别
	let router = new VueRouter({});
	router.map({
		'/goods': {
			component: goods
		},
		'/ratings': {
			component: ratings
		},
		'seller': {
			component: seller
		}
	});
	router.start(app, '#app');

三:路由地址包含有#的问题

1.vue-router默认hash模式,需要设置 mode: 'history',同时还需要在后台进行配置,详情请看vue-router 2中文手册的HTML5 History 模式

四:嵌套路由问题

1.上一级的路由必须设置路由入口router-view
//写法1:
	import Vue from 'vue';
	import VueRouter from 'vue-router';
	import VueResource from 'vue-resource';
	................
	import frame from 'components/frame.vue';//设置路由入口
	import goods from 'components/goods/goods.vue';
	import ratings from 'components/goods/ratings.vue';
	import seller from 'components/goods/seller.vue';
	-----------------------------------------------------
	//并且配置路由器规则
	const routes =[
		{
			path:'/goods',
			component: frame,
			children: [
				{ path: '/',component: goods},
				{ path: 'ratings',component:ratings}}
			]
		},
		'seller': {
			component: seller
		}
	];
	const router = new VueRouter({
	  	routes
	});
	-----------------------------------------------------
	//frame.vue文件:
	<template>
	  <div class="routes">
	      <router-view></router-view>
	  </div>
	</template>

	//写法2:
	import Vue from 'vue';
	import VueRouter from 'vue-router';
	import VueResource from 'vue-resource';
	................
	import goods from 'components/goods/goods.vue';
	import ratings from 'components/goods/ratings.vue';
	import seller from 'components/goods/seller.vue';
	-----------------------------------------------------
	//并且配置路由器规则
	const routes =[
		{
			path:'/goods',
			component: goods,
			children: [
				{ path: 'ratings',component:ratings}}
			]
		},
		'seller': {
			component: seller
		}
	];
	const router = new VueRouter({
	  	routes
	});
	-----------------------------------------------------
	//goods.vue文件必须含有:
	<router-view></router-view>

五:设置网页title的问题

1.使用vue-wechat-title插件:npm install vue-wechat-title
//使用方法
	//1、头部引入该插件
	import VueWechatTitle from 'vue-wechat-title';
	//2、在路由中配置meta值
	const routes =[
		{
			path:'/shop',
			meta: {title: '我的店铺'},
			component: shop
		}
	];
	const router = new VueRouter({
	  	routes
	});
	//3、在页面中添加v-wechat-title
	<router-view v-wechat-title="$route.meta.title"></router-view>

六:当前路由激活时状态设置

1.在设置路由中设置linkActiveClass
//使用方法
	const router = new VueRouter({
		linkActiveClass: 'active',//激活时添加的类名:active
	  	routes
	})



Logo

前往低代码交流专区

更多推荐