1.首先,安装vue-router
npm install vue-router --save-dev
2.创建一个route.js文件
// 1. 定义路由组件
// 可以自己写的,或者导入的,大部分是导入的
const Foo = { template: ‘<div>foo</div>‘ }
const Bar = { template: ‘<div>bar</div>‘ }
// 2. 定义路由规则
// 每个路由映射一个组件
const routes = [
{ path: ‘/foo‘, component: Foo },
{ path: ‘/bar‘, component: Bar }
]
//导出使用
export default=routes;
3.在入口文件中进行路由的使用
import Vue from ‘vue‘
import VueRouter from ‘vue-router‘
import routes from "./Admin/route/route.js";//导入路由文件
//使用插件
Vue.use(VueRouter)
//实例化
const router = new VueRouter({
routes,
mode: ‘history‘
})
//使用
new Vue({
el: ‘#app‘,
template: "<div><router-view></router-view></div>",
router
})
4.在组件文件中的使用,获取参数,跳转等操作
// Home.vue
<template>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- use router-link component for navigation. -->
<!-- specify the link by passing the `to` prop. -->
<!-- `<router-link>` will be rendered as an `<a>` tag by default -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- route outlet -->
<!-- component matched by the route will render here -->
<router-view></router-view>
</div>
</template>
<script> export default { computed: { username () { // We will see what `params` is shortly return this.$route.params.username } }, methods: { goBack () { window.history.length > 1 ? this.$router.go(-1) : this.$router.push(‘/‘) } } }
</script>
5.路由方法Api
router.push(location, onComplete?, onAbort?)
例子:
const userId = 123
router.push({ name: ‘user‘, params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// This will NOT work
router.push({ path: ‘/user‘, params: { userId }}) // -> /user
router.go(n)
例子:
// go forward by one record, the same as history.forward()
router.go(1)
// go back by one record, the same as history.back()
router.go(-1)
原文:https://www.cnblogs.com/xuqp/p/9199338.html