第一步 : 安装router ---->官方文档
第二步 : 创建文件夹router,并创建一个index.js文件
第三步 : 进行 index.js 的相关配置
// 以前vue2是
// import Router from 'vue-router'
// 引入 createRouter 替换new Vue
import {createRouter,createWebHashHistory} from "vue-router"
import Home from "../views/Home.vue" //引入路由组件
const router = createRouter({ //createRouter vue2中是 new Vue
history : createWebHashHistory(), //createWebHashHistory ,v3文档 API里有 ,将模式修改 ,Vue2中是mode :history
routes: [{ //配置路由规则
name: 'home',
path: '/', //默认路径
component: Home
},
{
name: 'about',
path: '/About',
component: ()=> import('../views/About.vue') //动态路由的写法
}
]
})
export default router
第四步 : 创建两个子路由文件,并在src目录下创建文件夹views
第五步 : 在main.js中进行相关配置
// import Vue from 'vue'
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
let app = createApp(App) 一.创建
import router from "./router/index.js"
console.log(app);
// app.directive('focus',{ //全局注册自定义指令
// // 将绑定的元素插入到DOM中
// mounted : function(el){
// // 聚焦元素
// el.focus()
// }
// })
// vue3全局注册组件的写法
// 在vue2中是将Vue.user(router)写到routers文件夹的index.js中,v3不是
app.use(router).mount('#app') //使用,替换new Vue
// new Vue({ vue2中的写法
// router,
// render: h => h(App),
// }).$mount('#app')
编程式路由的基础写法
<template>
<div class="app">
<!-- <router-link to='/' v-slot="{btnhome} ">Home</router-link>
<router-link to='/about' v-slot="{btnhome} ">About</router-link>
-->
<button @click='gohome'>Home</button>
<button @click='goabout'>About</button>
<router-view></router-view>
</div>
</template>
<script setup>
import {useRouter} from 'vue-router';
const router = useRouter() //返回 router 实例。相当于在模板中使用 $router。必须在 setup() 中调用。
const gohome = () => {
// this.$router.push('home') vue2的写法
router.push('/')
}
const goabout = () => {
// this.$router.push('home') vue2的写法
router.push('/about')
}
</script>
<style>
</style>