Vue 路由router

发布时间 2023-04-30 21:22:17作者: 醒醒起来

简单案例:

App.vue是核心组件,其中的<router-link>相当于a标签,to相当于href,export是暴露函数,这样某组件才能被其他组件识别到

代码:

<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>
View Code

index.js中通过routes定义路由路径和要跳转的组件

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
    }
  ]
})
View Code

Main.vue相当于后端的jsp页面,前端的html页面

<template>
<h1>我是主页</h1>
</template>
<script>
export default {
  name: "Main"
}
</script>
<style scoped>
</style>
View Code

Content.vue

<template>
<h1>我是内容页</h1>
</template>
<script>
//暴露
export default {
  name: "Content"
}
</script>
<style scoped>
</style>
View Code

在终端运行之

npm run dev

运行结果:

 

 


流程:用户在App.vue核心点击超链--> 到index.js拿到路由映射路径 --> 寻找组件目录下对应的.vue文件,index.js相当于中间商

注意:main.js文件的作用相当于全局配置,配置路由和核心组件App.vue,一旦确定一般不用再改动