编写router.js,千万注意routes不是routers
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import home from '../components/home.vue'
import about from '../components/about.vue'
import child from '../child/child.vue'
// 定义路由
const routes = [
// vue2.x 一致
{ path: '/home', name: 'home', component: home },
{ path: '/about', name: 'about', component: about },
{ path: '/child', name: 'child', component: child }
]
// 创建路由实列
const router = createRouter({
// history: routerHistory, // history
history: createWebHashHistory(), // hash
routes,
});
export default router;
main.js中全局挂载路由文件,切记先app.use挂载,再mount初始化,顺序不要搞错了
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/router'
const app = createApp(App)
app.use(router)
app.mount('#app')
vue文件中的用法,router-link路由和编程式路由,router-view标签用来定义页面渲染的位置(新页面放在当前页面的哪里)
<template>
<div id="app">
<button @click="home">home</button>
<button @click="about">about</button>
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
</div>
<router-view/>
</template>
<script setup>
import router from './router/router';;
const home=()=>{
router.push({'name':'home'})
}
const about=()=>{
router.push({'name':'about'})
}
</script>