VueRouter之HelloWorld

添加包依赖

javascript 复制代码
  "dependencies": {
    "vue": "^2.7.7",
    "vue-router": "^3.5.4"
  },

Vue2对应VueRouter3

Vue3对应VueRouter4

在src/router/index.js中配置路由

javascript 复制代码
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const router = new VueRouter({
    mode: 'history',
    base: import.meta.env.BASE_URL,
    routes: [
        {
        },

    ]
})

export default router

在main.js中引入router

javascript 复制代码
import Vue from 'vue'

import App from './App.vue'
import router from './router'


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

我们做一个简单的案例

点击首页、关于,调到对应的组件

目录结构如下

App.vue

html 复制代码
<script setup>
</script>

<template>
  <div class="app-container">
    <h1>App根组件</h1>
    <router-link to="/home">首页</router-link>
    <router-link to="/about">关于</router-link>
    <hr>
    <router-view></router-view>
  </div>
</template>

<style scoped>
.app-container {
  text-align: center;
  font-size: 16px;
}

.app-container a {
  padding: 10px;
  color: #000;
}

.app-container a.routerr-link-active {
  color: #fff;
  background-color: #000;
}
</style>

HomeView.vue

html 复制代码
<script>
export default {
  name: "HomeView"
}
</script>

<template>
  <div class="home-container">
    <h3>Home组件</h3>
  </div>

</template>

<style scoped>
.home-container {
  min-height: 150px;
  background-color: #f2f2f2;
  padding: 15px;
}

</style>

AboutView.vue

html 复制代码
<script>
export default {
  name: "AboutView"
}
</script>

<template>
  <div class="about-container">
    <h3>About组件</h3>
  </div>

</template>

<style scoped>
.about-container {
  min-height: 150px;
  background-color: #f2f2f2;
  padding: 15px;
}

</style>

index.js

javascript 复制代码
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const router = new VueRouter({
    mode: 'history',
    base: import.meta.env.BASE_URL,
    routes: [
        {
            path: '/',
            redirect: '/home'
        },
        {
            path: '/home',
            name: 'home',
            component: () => import('../views/HomeView.vue')
        },
        {
            path: '/about',
            name: 'about',
            component: () => import('../views/AboutView.vue')
        },

    ]
})

export default router
相关推荐
我命由我123458 小时前
CesiumJS 笔记 - 获取容器中心点、Cartesian3 clone 方法、修改 Cartesian3 对象的高度
前端·javascript·css·前端框架·html·html5·js
Hopebearer_9 小时前
页面突然只剩 DOM?一次静态资源版本错配排查
前端·部署
抱抱宝9 小时前
Agent-study项目教程(03):手写 Mini-ReAct Agent(不依赖框架)
javascript·人工智能·gpt·react.js·prompt·agent
东风破_10 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
用户9385156350710 小时前
Next.js 笔记系统(二):Redis 数据服务与侧边栏组件拆分实战
javascript·全栈
java1234_小锋11 小时前
Vue3专题 - 组件基础
vue.js·vite
圣殿骑士-Khtangc11 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
BigTopOne12 小时前
【ijkplayer】 硬解码流程
前端
kyriewen12 小时前
DeepSeek Harness开源第一天我就上手了——和Claude Code的差距比想象中大
前端·ai编程·deepseek
捡田螺的小男孩13 小时前
什么是 Skill?手把手带你写一个简单有用的 Skill!
前端·后端·程序员