Vue Router(第一章)

55 阅读1分钟

vue是单页面,不会有那么多html,

vue路由可以实现不同的url访问不同的内容,实现多视图单页面应用

router.js

import {
  createRouter,
  createMemoryHistory,
  createWebHistory,
  createWebHashHistory,
} from 'vue-router'

const routes = [
  // import导入组件,路由懒加载,进入了该路由才会加载这份js文件
  { path: '/', component: () => import('../components/A.vue') }, 
  { path: '/b', component: () => import('../components/B.vue') },
]

const router = createRouter({
  // history: createWebHistory(), // 不带 # 的 history 模式
  history: createWebHashHistory(), // 带 # 的 hash 模式
  routes,
})

export default router

main.js挂载

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)

app.mount('#app')

页面使用

<template>
  <div>
    <h1>我是首页</h1>

    <router-link to="/">去A</router-link>
    <router-link to="/b" style="margin-left: 10px">去B</router-link>

    <hr />
    <router-view></router-view>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
</script>
<style scoped lang="scss"></style>

router-link

创建链接,to='/b' 属性就是去的url地址

router-view

就是路由占位符,您要在哪个区域下创建切换路由展示不同url的,要放一个这个