Vue2配置路由

1、安装Vue Router

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

npm install vue-router@3

2、新增router 的index.js

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

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 中注册路由,导入并使用路由。

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标签

<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实现路由跳转

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值