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>
  
相关推荐
前端开发与ui设计的老司机11 分钟前
UI前端与数字孪生结合实践探索:智慧物流的货物追踪与配送优化
前端·ui
全能打工人13 分钟前
前端查询条件加密传输方案(SM2加解密)
前端·sm2前端加密
海天胜景35 分钟前
vue3 获取选中的el-table行数据
javascript·vue.js·elementui
翻滚吧键盘1 小时前
vue绑定一个返回对象的计算属性
前端·javascript·vue.js
苦夏木禾1 小时前
js请求避免缓存的三种方式
开发语言·javascript·缓存
超级土豆粉1 小时前
Turndown.js: 优雅地将 HTML 转换为 Markdown
开发语言·javascript·html
秃了也弱了。1 小时前
Chrome谷歌浏览器插件ModHeader,修改请求头,开发神器
前端·chrome
乆夨(jiuze)2 小时前
记录H5内嵌到flutter App的一个问题,引发后面使用fastClick,引发后面input输入框单击无效问题。。。
前端·javascript·vue.js
忧郁的蛋~2 小时前
HTML表格导出为Excel文件的实现方案
前端·html·excel
小彭努力中2 小时前
141.在 Vue 3 中使用 OpenLayers Link 交互:把地图中心点 / 缩放级别 / 旋转角度实时写进 URL,并同步解析显示
前端·javascript·vue.js·交互