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>
  
相关推荐
JIngJaneIL1 小时前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
ttod_qzstudio2 小时前
深入理解 Vue 3 的 h 函数:构建动态 UI 的利器
前端·vue.js
芳草萋萋鹦鹉洲哦2 小时前
【elemen/js】阻塞UI线程导致的开关卡顿如何优化
开发语言·javascript·ui
_大龄2 小时前
前端解析excel
前端·excel
1***s6322 小时前
Vue图像处理开发
javascript·vue.js·ecmascript
一 乐2 小时前
应急知识学习|基于springboot+vue的应急知识学习系统(源码+数据库+文档)
数据库·vue.js·spring boot
槁***耿2 小时前
JavaScript在Node.js中的事件发射器
开发语言·javascript·node.js
一叶茶2 小时前
移动端平板打开的三种模式。
前端·javascript
前端大卫2 小时前
一文搞懂 Webpack 分包:async、initial 与 all 的区别【附源码】
前端
U***49832 小时前
JavaScript在Node.js中的Strapi
开发语言·javascript·node.js