首先在当前项目下安装依赖包,运行npm install vue-router 则package.json中添加了vue-router
此时在src 下的index.js主程序中引入vue-router,同时告诉Vue使用此路由配置
1 import VueRouter from "vue-router"
2 Vue.use(VueRouter);
在index.js里面引入需要配置的组件的信息
1 import Vmain from "@/components/Vmain.vue"
2 import Vcourse from "@/components/Vcourse.vue"
3 import Vmarke from "@/components/Vmarke.vue"
实例化一个路由对象,并把配置路由列表传进去,路由可以去除默认的井号配置 mode:"history"
1 const router=new VueRouter({
2 mode:"history",
3 routes:[
4 {path:"/",component:Vmain},
5 {path:"/Vcourse",component:Vcourse},
6 {path:"/Vmarke",component:Vmarke},
7 ]
8 });
把当前路由对象挂载到Vue对象中去,在键值相同的情况下,可以省略用,代替
1 new Vue({
2 el: '#app',
3 router,
4 components: { App },
5 template: '<App/>'
6 });
在父组件app.vue里面,如果想用子组件路由,则必须加入 <router-view></router-view>路由出口
然后可以用<router-link to=" ">xxx</router-link> 去替代<a href="">xxx</a>
默认会加载出 "/"对应的路由