Vue2配置路由

1、安装Vue Router

如果你还没有安装 Vue Router,请先安装它。

bash 复制代码
npm install vue-router@3

2、新增router 的index.js

创建路由配置文件(例如 src/router/index.js),并在其中定义路由规则。

javascript 复制代码
import Vue from "vue";
import VueRouter from "vue-router";
import newPage from "../views/newPage.vue";
import indexPage from "../views/indexPage.vue";



Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        name: 'indexPage',
        component: indexPage
      },
    {
      path: '/newPage',
      name: 'newPage',
      component: newPage
    },
  ];
const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
  });
  
export default router;

3、注册路由到主应用

在 main.js 中注册路由,导入并使用路由。

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

new Vue({
  router,//注册路由
  render: h => h(App),
}).$mount('#app')

4、修改app.vue

注意要有router-view标签

html 复制代码
<template>
  <div id="app">
  <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>

5、使用

两种使用方法:

1、使用router-link标签直接实现路由跳转

2、使用this.$router.push实现路由跳转

html 复制代码
<template>
  <div class="newPage">
    <h1>Vue基础知识</h1>
    <!-- 使用按钮并添加事件处理器 -->
    <router-link to="/onePage">第一章 </router-link>
    <button @click="goToOne">第一章 </button><br><br>
    
  </div>
</template>
  
<script>
export default {
  name: 'newPage',
 
  methods: {
    goToOne() {
      console.log('goToOne');
      // 使用编程式导航跳转到 /onePage 页面
      this.$router.push({
        path: '/onePage'
      })

    },
   
  }
  
}
</script>
  
<style scoped></style>
  
相关推荐
Yao80625 分钟前
MinIO自建对象存储,省OSS费用的完整方案
前端·后端
2501_9339232533 分钟前
设计网页的时候加载不出来怎么办?认识常见的状态码
前端·spring
only-lucky40 分钟前
QML深入学习五(Controls模块)
前端·javascript·学习
程序员黑豆1 小时前
鸿蒙应用开发之路由:Router 页面路由使用教程
前端·harmonyos
gyx_这个杀手不太冷静1 小时前
Agent开发进阶指南(第 2 章):Agent 运行全流程拆解、上下文窗口、流式输出、记忆系统与 Function Call 实战
前端·架构·agent
anyup1 小时前
像这种问题千万别自己动手,否则你可太看不起 AI 了
前端·架构·trae
hunterandroid2 小时前
[鸿蒙从零到一] HarmonyOS Web 组件与 JSBridge 通信实战:从页面加载到安全协议
前端
xingren2 小时前
「拍摄器」UI 特效 - 在 Winform/WPF/WinUI3/Avalonia/Web 的实现
前端
其美杰布-富贵-李2 小时前
第 5 篇:Object3D、Group 与场景树
javascript·three.js
leslie1182 小时前
npm常用命令
前端·npm