简单案例:
App.vue是核心组件,其中的<router-link>相当于a标签,to相当于href,export是暴露函数,这样某组件才能被其他组件识别到
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div id="app"> <img src="./assets/logo.png"> <h1>hello!!!!!!!!!!!!!</h1> <!-- 路由路径 这里!!!--> <router-link to="/main">首页</router-link> <router-link to="/content">内容页</router-link> <router-view></router-view> </div> </template> <script> export default { name: 'App' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
index.js中通过routes定义路由路径和要跳转的组件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import Vue from "vue";
import VueRouter from "vue-router";
import Content from "../components/Content.vue";
import Main from "../components/Main.vue";
//安装路由
Vue.use(VueRouter);
//配置导出路由
export default new VueRouter({
routes:[
{
//路由路径,这里!!!
path:'/content',
name:'content',
//跳转的组件
component:Content
},
{
//路由路径
path:'/main',
name:'content',
//跳转的组件
component:Main
}
]
})
Main.vue相当于后端的jsp页面,前端的html页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <h1>我是主页</h1> </template> <script> export default { name: "Main" } </script> <style scoped> </style>
Content.vue
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <h1>我是内容页</h1> </template> <script> //暴露 export default { name: "Content" } </script> <style scoped> </style>
在终端运行之
npm run dev
运行结果:
流程:用户在App.vue核心点击超链--> 到index.js拿到路由映射路径 --> 寻找组件目录下对应的.vue文件,index.js相当于中间商
注意:main.js文件的作用相当于全局配置,配置路由和核心组件App.vue,一旦确定一般不用再改动