一、编写router配置项(在router文件夹的index.js文件中编写)
import Vue from 'vue'//引入vue
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
// import HomeView from '@/views/HomeView.vue'
// 使用router插件
Vue.use(VueRouter)
//创建router对象,匹配路由规则
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
}
]
const router = new VueRouter({//实例化对象
routes,
// mode:'hash'
mode:'history'
})
export default router
// 总结:1安装路由 2写路由规则 3挂载main.js 4根组件中写router-link组件和路由出口
二、在main.js中进行引入和挂载
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
三、在根组件中使用
<template>
<div id="app">
<nav>
<!-- <router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> -->
<!-- tag="h2"更改a标签 -->
<h2 @click="gohome">Home</h2>
<h2 @click="goabout">About</h2>
</nav>
<!-- 路由出口 :指定展示位置 -->
<router-view/>
</div>
</template>
<script>
export default {
name:'APP',
methods: {
/* 第一种
gohome() {
this.$router.push('/')
},
goabout() {
this.$router.push('/about')
} */
/* 第二种 */
// gohome() {
// this.$router.push({path:'/'})
// },
// goabout() {
// this.$router.push({path:'/about'})
// }
/* 第3种 */
// gohome() {
// this.$router.push({name:'home'})
// },
// goabout() {
// this.$router.push({name:'about'})
// }
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
}
nav a {
font-weight: bold;
color: #2c3e50;
}
nav a.router-link-exact-active {
color: #42b983;
}
</style>