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
相关推荐
小码哥0681 小时前
租房平台源码部署验收:房源样例、区域字典与看房预约逐项验证
前端·javascript·vue.js·租房小程序·租房系统·租房软件
htzyl2061 小时前
JS原型链与继承:class 底下到底是什么
前端·javascript·ecmascript 6
一条Go1 小时前
15 套品牌色 + 双模式:把颜色关进三层 token
前端·github
htzyl2062 小时前
JS-关于闭包捕获与释放
前端·javascript
狗头大军之江苏分军2 小时前
《潮水漫过十七岁》好久没写了
前端·javascript·后端
console.log('npc')2 小时前
Python第9课 类学习笔记,前端js语法对照
前端·python·学习
橙序员小站2 小时前
没有AI,我根本不知道同事有多苦
前端·微信小程序
ssshooter4 小时前
Replit 项目本地跑:一份实测过的改造清单
前端·后端·设计模式
濮水大叔4 小时前
Cabloy/Zova 与 Next.js 的布局组件差异:从目录嵌套到路由应用壳
前端·typescript·next.js
蔓越莓曲奇4 小时前
给 DeepSeek Harness 换上 GTA 6 皮肤:Agent 一干活,通缉星级就亮
前端·javascript·开源