Skip to content

配置路由

在单页应用中,“路由”的主要作用是将浏览器的 URL 和用户看到的内容绑定起来。

vue 的路由是由 vue-router 库提供的,安装后使用。

bash
pnpm add vue-router@4

基础使用

js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router.js'
const app=createApp(App)
app.use(router)	
app.mount('#app')
js
import Home from './components/Home.vue'
import About from './components/About.vue'
import { createRouter, createWebHashHistory } from 'vue-router'	// 使用
export default createRouter({	// <!---->
  history: createWebHashHistory(),
  routes: [
    { path: '/home', component: Home },		// 关联路径和页面组件
    { path: '/about', component: About ,
    { path: '/', redirect: '/home' },		// 重定向根路径到 /home
  ],
})
vue
<template>
  <div class="app-container">
    <h2>App根组件</h2>
    <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: rgb(0, 0, 0);
  }
  .app-container a.router-link-active {
    color: rgb(224, 255, 49);
    background-color: black;
  }
</style>