在Vue3中安装并初始化vur-router
2021-08-02 本文已影响0人
缺月楼
Vue3
已经发布一段时间了,对比原来的版本,性能有较大的提升,对Ts
的支持更加友好,用法和原来的差不多,兼容Vue2
语法。今天对Vue3进行初探,用到了Vue
的几个核心组件。
不废话直接开干,用命令行创建Deno
。
我用的终端管理软件是 ConEmu一款强大的工具,
开始
-
在桌面创立新的项目文件夹 并用命令行进入该文件。
image.png
- 在该文件目录下安装构建工具
你还可以通过附加的命令行选项直接指定项目名称和你想要使用的模板。例如,要构建一个 Vite + Vue 项目,运行: 本文使用的就是指定版本。
# npm 6.x
npm init vite@latest my-vue-app --template vue
# npm 7+, 需要额外的双横线:
npm init vite@latest my-vue-app -- --template vue
# yarn
yarn create vite my-vue-app --template vue

-- 创建项目目录 --
执行 命令 cva xxx
项目名 或者create-vite-app xxx项目名
xxx项目名
随意起

- 初始化项目
进入项目
cd xi-ui-1
初始化 开始yarn
image.png
- 项目初期 跑起来
yarn dev
image.png
本地服务器跑起来了命令行执行如下命令 ,效果如下:
yarn dev



-
开始引入Vue-router 路由器 用于页面切换
使用命令行查看vue-router的所有版本
npm info vue-router versions

-- 安装vue-router
还是采用指定版本号的方式
yarn add vue-router@4.0.0-beta.3


重头戏来了 开始写代码

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
//添加以下代码 引入路由
import { createWebHashHistory, createRouter } from 'vue-router'
import laowang from './components/laowang.vue'
import laowang2 from './components/laowang2.vue'
const history = createWebHashHistory()
const router = createRouter({
history,
routes:[
//当访问根目录的时候 渲染的是 laowang这个组件 下面的一样的意思
{path:'/',component:laowang},
{path:'/xxx',component:laowang2}
]
})
const app = createApp(App)
app.use(router)
app.mount('#app')
- 在 App.vue 中 添加 <router-view> 和 <router-link >
<template>
<div>导航栏 |
<router-link to="/">laowang</router-link> |
<router-link to="/xxx">laowang2</router-link>
</div>
<hr>
<router-view/>
</template>
<script>
export default {
name: 'App',
}
</script>
最终效果如下 :

当点击laowang 或者laowang2的时候 下面的组件也会跳转