项目搭建
教程可参考→vite官方文档。
但目前已更新新版,命令有变化。新版网址。
全局安装create-vite-app:
yarn global add create-vite-app@version
//或者 npm install -g create-vite-app@version
创建项目
npm init vite-app project-name
//或者
yarn create vite-app project-name
//或者
cva project-name
vue-router的引入和初始化
安装vue-router:
yarn add vue-router
//或者
npm install vue-router
//需要指定版本号,加上@version即可。
初始化步骤:
- 在 main.ts 内引入、创建 history 对象。
- 在 main.ts 内引入、创建 router 对象。
- 引入
TypeScript(直接改成.ts文件)。 - 在 main.ts 内引入所有路由页面,router内完善{path:'xxx',component:xxx}。
- 在 main.ts 内加上
const app = createApp(App)
app.use(router)
app.mount("#app");
- 在APP.vue内添加
<router-view /> - 在APP.vue内添加
<router-link to="xxx">
代码示例:
//App.vue
<template>
<router-view />
</template>
<script lang="ts">
import { provide, ref } from "vue";
import { router } from "./router";
export default {
name: "App",
setup() {
const width = document.documentElement.clientWidth;
const asideVisible = ref(width <= 500 ? false : true);
provide("asideVisible", asideVisible);
router.afterEach(() => {
if (width <= 500) {
asideVisible.value = false;
}
});
},
};
</script>
在入口文件main.ts内,引入router,然后app.use(router)
//main.ts
import "./lib/you.scss";
import "./index.scss";
import { router } from "./router";
import { createApp } from "vue";
import App from "./App.vue";
import "github-markdown-css";
const app = createApp(App);
app.use(router);
app.mount("#app");
之后只需要在展示路由页面的地方写上<router-view/>即可,并用<router-link to="/doc">开始</router-link>来创建跳转。
可以将路由抽离出一个组件,然后在需要的组件内引入即可:
//router.ts
import { createWebHashHistory, createRouter } from "vue-router";
import Home from "./views/Home.vue";
import Doc from "./views/Doc.vue";
import SwitchDemo from "./components/SwitchDemo.vue";
import ButtonDemo from "./components/ButtonDemo.vue";
import DialogDemo from "./components/DialogDemo.vue";
import TabsDemo from "./components/TabsDemo.vue";
import Intro from "./views/Intro.vue";
const history = createWebHashHistory();
export const router = createRouter({
history: history,
routes: [
{ path: "/", component: Home },
{
path: "/doc",
component: Doc,
children: [
{ path: "", redirect: "/doc/intro" },
{ path: "intro", component: Intro },
{ path: "switch", component: SwitchDemo },
{ path: "button", component: ButtonDemo },
{ path: "dialog", component: DialogDemo },
{ path: "tabs", component: TabsDemo },
],
},
],
});
<router-view/>本质上是一个a标签。