新建项目
npm create vite@latest
安装vue-router
cd .\my-web\
npm install vue-router
在src -> components下新增(Home.vue)
<template>
<h1>我是主页</h1>
</template>
在src -> components下新增(Register.vue)
<template>
<h1>用户注册</h1>
</template>
在src -> components下新增(About.vue)
<template>
<h1>关于我们</h1>
</template>
在src -> components下新增(NotFound.vue)
<template>
<h1>404</h1>
</template>
在src下新建文件夹router,并在其下新建index.ts:
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../components/Home.vue'
import Register from '../components/Register.vue'
import About from '../components/About.vue'
import NotFound from '../components/404.vue'
const routes = [
{ path: '/', name: 'Home', component: Home },
{ path: '/register', name: 'Register', component: Register },
{ path: '/about', name: 'About', component: About },
{ path: '/:path(.*)', component: NotFound }
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
修改App.vue,使用router-link标签跳转,实际上底层是通过a链接进行跳转。
<template>
<div class="container">
<div class="header">
<ul class="p1">
<li>
<router-link to="/">主页</router-link>
</li>
<li>
<!-- <router-link to="/register">注册</router-link> -->
<a href="/register">注册</a>
</li>
<li>
<router-link to="/about">关于</router-link>
</li>
</ul>
</div>
<div class="content"><router-view /></div>
</div>
</template>
<style>
* {
margin: 0px;
padding: 0px;
}
.container {
width: 100%;
height: 100%;
}
.header {
width: 100%;
height: 10%;
padding-bottom: 200px;
}
.content {
width: 100%;
height: 90%;
position: absolute;
bottom: 0;
}
ul {
list-style-type: none;
/*清楚项目符号*/
}
li {
margin: 0 2px;
/*并列显示*/
float: left;
}
/*鼠标经过超链接的样式*/
a:hover {
color: #444;
background: #f99;
border-color: #fff#aaa#aaa#fff;
}
a {
/*完全清除超链接下划线效果*/
text-decoration: none;
border: solid 1px;
padding: 0.4em 0.8em;
color: green;
background: transparent;
border-color: #bbb#fff#fff#aaa;
/*解决IE浏览器无法显示问题*/
zoom: 1;
}</style>
修改main.ts
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(ElementPlus)
app.use(router)
app.mount('#app')
运行项目npm run dev
查看效果
注意
如出现以下报错
在vue.config.js中添加
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false
})