认识 Vue Router 路由

Vue Router 是 Vue.js 的官方路由器。它与 Vue.js 核心深度集成,使使用 Vue.js 轻松构建单页应用程序变得轻而易举。功能包括:

可以实现一些页面的跳转,例如我们头部的内容是不变的,内容部分需要根据链接改变

  • 嵌套路线/视图映射
  • 模块化,基于组件的路由器配置
  • 路由参数,查询,通配符
  • 查看由Vue.js过渡系统提供动力的过渡效果
  • 细粒度的导航控制
  • 与自动活动CSS类的链接
  • HTML5历史记录模式或哈希模式,在IE9中具有自动回退
  • 可自定义的滚动行为

安装步骤:

vue-router 是一个插件包

npm install vue-router --save-dev

安装后如果有一些问题,根据提示,输入对应命令即可

创建好项目后,删掉默认的 HelloWorld那个组件,然后再 components 中新建两个自定义组件,例如我创建的 F.vue 和 M.vue 前者是一个子页面,后者代表主页面。

F.vue

复制代码
<template>
  <h1>页面</h1>
</template>

<script>
  export default {
    name: "FirstDemo.vue"
  }
</script>

<style scoped>

</style>
复制代码

 

M.vue

复制代码
<template>
  <h1>首页</h1>
</template>

<script>
  export default {
    name: "Main.vue"
  }
</script>

<style scoped>
</style>
复制代码

接着创建 router 文件夹,以及其中的 index.js 主配置

复制代码
import Vue from 'vue'
import VueRouter from 'vue-router'
import F from '../components/FirstDemo'
import M from '../components/Main'

Vue.use(VueRouter);

export default new VueRouter({
  routes: [
    {
      // 路由路径
      path: "/firstDemo",
      name: 'firstDemo',
      // 跳转的组件
      component: FirstDemo
    },
    {
      // 路由路径
      path: "/main",
      name: 'main',
      // 跳转的组件
      component: Main
    }
  ]
})
复制代码

 

修改 main.js 这个入口文件

复制代码
import Vue from 'vue'
import App from './App'
import router from './router'

new Vue({
  el: '#app',
  //配置路由
  router,
  components: {App},
  template: '<App/>'
})
复制代码

 

写页面,引入链接

复制代码
<template>
  <div id="app">
    <h1>理想</h1>
    <router-link to="/main">首页</router-link>
    <router-link to="/firstDemo">页面</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>
复制代码

 

posted @   四水呐  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示