一、路由的使用
二、安装路由
npm i vue-router
2. 配置路由
代码如下(示例):
第一步引入vue和router
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
第二步创建路由组件
import Home from '@/views/Home.vue';
import User from '@/views/User.vue';
import Main from '@/views/Main.vue';
import Mall from '@/views/Mall.vue';
import PageOne from '@/views/PageOne';
import PageTwo from '@/views/PageTwo';
//在点击同一个跳转路由的时候,点一下并没有报错,但是多点几下就会报错解决方案
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
第三步将路由与组件映射
定义路由
每个路由应该映射一个组件。 其中"component" 可以是
通过 Vue.extend() 创建的组件构造器,
或者,只是一个组件配置对象。
const routes = [
//主路由
{
path: '/',
component: Main,
redirect: 'home' //重定向
,
children: [
//子路由
{
path: 'Home',
component: Home //首页
},
{
path: 'User',
component: User //用户管理
},
{
path: 'Mall',
component: Mall //商品管理
},
{
path: 'Page1',
component: PageOne //页面1
},
{
path: 'Page2',
component: PageTwo //页面2
}
]
}
]
第三步. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
routes // (缩写) 相当于 routes: routes
})
export default router
3. 路由挂载
import Vue from 'vue'
import App from './App.vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from "./router";
import store from "./store"
import './api/mock'
Vue.use(ElementUI);//全局引入
Vue.config.productionTip = false
new Vue({
router,//挂载
store,
render: h => h(App),
}).$mount('#app')
4. 路由跳转两类
1.<router-link tag='li' to='路径' / >
<router-link to="Router" tag="li" active-class="active">路由</router-link>
因为router-link点击事件进不去 vue自带active-class的切换样式
2. 编程式跳转
this.$router.push({path:路径) 注意 跳转自路由 /shop/goods
this.$router.push('/b');
this.$router.push({name:'路由name名称'})
this.$router.replace() 刷新 替换当前页面 没有历史记录 不能返回 会返回到根路径
this.$router.go() 前进后退 正负1 前进后退一级
5. 子路由嵌套
{
path:'/a',
component:{A},
children:[
{path:xx,component:xxx}
]
}
2. 在A 组件中配置 router-view
3. 子路由的默认路由
总结
例如:以上就是今天要讲的内容,本文仅仅简单介绍了路由的安装已经配置和简单的基本使用