03 Vue3 Vue Router 4.x入门指南

Technology

  • vue 3 安装 npm install @vue/cli
  • vue-router 4 安装 npm install vue-router@4

目录结构

├── App.vue
├── assets
│   └── logo.png
├── components
│   ├── About.vue
│   └── Home.vue
├── main.js
└── router.js

调用关系

main.js -> router.js 
        -> App.vue -> components/About.vue
                   -> components/Home.vue

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'            // 引用 router.js 配置文件

createApp(App).use(router).mount('#app') // 启动实例

createApp(App).use(router).mount('#app') 分步骤对应如下代码语句:

  1. const app = Vue.createApp({}) // 创建并挂载根实例
  2. app.use(router) // 确保 use 路由实例,使整个应用支持路由。
  3. app.mount('#app') // 将 App.vue 渲染结果挂载到id为app的标签下

router.js

import { createWebHistory, createRouter } from "vue-router"; // 引用 vue-router 导入 createWebHistory, createRouter 方法

const routes =  [
    {
      path: "/home",                                   // 路由的路径 
      name: "home",                                    // 路由的名称 
      component: () => import("./components/Home.vue") // 路由的组件  
    },
    {
      path: "/about",                                  
      name: "about",
      component: () => import("./components/About.vue")
    }
  ];

  // 创建路由实例并传递 `routes` 配置
  const router = createRouter({
    history: createWebHistory(),  // 内部提供了 history 模式的实现,这里使用 hash 模式
    routes,                       // `routes: routes` 的缩写 
  });

  export default router;          //   

App.vue

<template>
  <ul>
    <li> <router-link to="/home"> Go to Home </router-link> </li>
    <li> <router-link to="/about"> Go to About </router-link> </li>
  </ul>

  <router-view/>
</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>

  1. router-link 这里用来替代HTML中的 a 标签,Vue Router 可以在不重新加载页面的情况下更改 URL,处理 URL 的生成以及编码
  2. router-view 显示与 url 对应的组件

components/home.vue

<template>
    <div>
        This is Vue Home Page !
    </div>
</template>

<script>
export default {
    name: "Home"
}
</script>

<style lang="stylus" scoped>
</style>

components/about.vue

<template>
    <div>
        This is Vue Home Page !
    </div>
</template>

<script>
export default {
    name: "Home"
}
</script>

<style lang="stylus" scoped>
</style>

最后在vue项目目录运行命令 npm run serve,使用浏览器访问 http://127.0.0.1:8080 点击Go to Home 和Go to About 会看到以下不同的页面(注意页面内容的变化):

image
image

打开开发者模式,会发现:
router-link 被渲染成HTML的 <a href=/xxx> 的标签
router-view 被渲染成引用子组件的内容

参考

  1. Vue Router 4.X 中文参考文档 https://next.router.vuejs.org/zh/guide/
  2. Vue 3 CRUD example with Axios & Vue Route https://bezkoder.com/vue-3-crud/
  3. P78【Vue和服务端交互】vue-router的使用 https://www.bilibili.com/video/BV14r4y1w7F5?p=78
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。