使用Vue-CLI从零搭建企业级项目实战Vue3全家桶
使用Vue CLI从零搭建企业级项目实战(Vue3+全家桶)
一篇关于 Vue3 项目搭建的博客文章。下面的示例包含了以下内容:
- 使用 Vue CLI 创建项目
- 安装并使用 axios 进行 API 请求
- 配置 vue-router 实现路由跳转
- 全局引入 ant-design-vue 组件库
Vue Cli脚手架使用
Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统
配置npm淘宝源(默认国外源,下载依赖较慢)
#设置淘宝源
npm config set registry https://registry.npm.taobao.org --global
#查看源
npm config get registry
命令安装: npm install -g @vue/cli@4.5.12
检查版本: vue -V
创建项目: vue create <项目名称>
选择Vue3项目
运行项目: npm run serve
访问
创建项目
首先使用 Vue CLI 创建项目(默认生成 Vue3 版本):
vue create vue-demo
进入项目目录后,安装所需的依赖包:
npm install axios vue-router ant-design-vue
Axios 介绍使用
官方文档:
在前端页面展示的数据大多数都是通过访问一个API获取的,做这件事的方法有好几种,例如 jquery ajax、vue-resource、axios,而vue-resource是vue插件,但3版本不再更新,目前官方 推荐主流的axios,aixos是一个http请求库。
安装axios: npm install axios
在组件中导入并使用
import axios from 'axios'
GET请求
- 使用 axios.get发起GET请求。
- 使用 .then 获取响应数据。
- 使用catch 异常处理
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png"/>
<button type="button" @click="getData()">获取后端数据</button>
{{ data }}
<p v-if="error" style="color: red;">连接服务器失败,请稍后再试!"</p>
</div>
</template>
<script>
// 导入话实例化对象
// import axios from "axios"
import axios from "axios"
import {onMounted, ref} from "vue"
export default {
setup() {
const data = ref('')
const error = ref(false)
function getData() {
axios.get('http://httpbin.org/get')
.then(res => {
data.value = res.data
console.log(res)
}).catch(res => {
error.value = true
console.log(res)
})
}
// 生命周期钩子
onMounted(() => {
getData()
console.log('挂载完成')
})
return {
error,
getData,
data
}
}
}
</script>
POST提交
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png"/>
<h1>欢迎访问管理后台</h1>
<form action="#">
用户名:<input type="text" v-model="form.username"/>
密码:<input type="password" v-model="form.password"/>
<button @click="loginBtn">登录</button>
</form>
<p style="color: red;" v-if="notice">用户名和密码不能为空"</p>
</div>
</template>
<script>
import axios from "axios"
import {ref, reactive} from "vue";
export default {
name: "Home",
setup() {
const form = reactive({
username: '',
password: ''
})
const notice = ref(false)
function loginBtn() {
if (form.username === '' || form.password === '') {
notice.value = true
} else {
axios.post('http://httpbin.org/post', form).then(res => {
console.log(res)
})
}
}
return {
form,
notice,
loginBtn
}
}
}
</script>
自定义实例 自定义实例默默认值认值
有时候服务端接口有多个地址,就会涉及请求的域名不同、配置不同等,这时自定义实例可以很好解决。
创建src/request/index.js文件,定义实例
import axios from "axios";
const instance = axios.create({
baseURL: "https://httpbin.org",
timeout: 1000,
// headers: { 'X-Custom-Header': 'foobar' }
});
// 拦截器 ,请求拦截
instance.interceptors.request.use(
config => {
// 在发送请求之前做些什么
config.headers['Test-Header'] = '123456'
return config;
},
error => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 拦截器 ,响应拦截
instance.interceptors.response.use(
response => {
// 对响应数据做点什么
return response;
},
error => {
// 对响应错误做点什么
return Promise.reject(error);
}
);
export default instance;
拦截器可以拦截每一次请求和响应,然后进行相应的处理。
请求拦截应用场景:
发起请求前添加header
响应拦截应用场景:
统一处理API响应状态码200或非200的提示消息
统一处理catch异常提示信息
Vue路由路由:Vue Router
Vue Router使用
Vue Router 是 Vue.js (opens new window)官方的路由管理器。
安装
npm install vue-router
创建src/router/index.js文件及目录,之后前端的路由都将维护在此文件中
使用流程
开发页面(组件)
定义路由,src/router/index.js
import { createRouter, createWebHistory } from "vue-router";
// 引入组件,一开是就会引入,即使不进入页面,也会加载组件
import Home from "@/views/Home.vue";
const routes = [
{
path: "/home",
name: "Home",
component: Home,
},
{
path: "/about",
name: "About",
// 引入组件,懒加载,只有在打开页面的时候才会加载
component: () => import("@/views/About.vue"),
},
{
path: "/login",
name: "Login",
// 引入组件,懒加载,只有在打开页面的时候才会加载
component: () => import("@/views/Login.vue"),
},
];
// 创建一个路由实例
const router = createRouter({
// 使用基于hash的路由历史模式
history: createWebHistory(),
// 定义路由配置数组
routes: routes,
// 配置路由模式
mode: "history",
});
// 导出路由实例以便在其他模块中使用
export default router;
组件使用路由,src/App.vue
<template>
<img alt="Vue logo" src="./assets/logo.png">
<div>
<!-- 使用router-link组件来导航 -->
<!-- 通过传入 to 属性制定链接 -->
<!-- router-link 默认会被渲染成一个a标签 -->
<router-link to="/home">Home</router-link>
<br>
<router-link to="/about">About</router-link>
</div>
<!-- 路由占位符,路由匹配到的组件都会在这里展示 -->
<router-view />
</template>
src/main.js种导入router
// {} 导入的是组件的方法
import { createApp } from 'vue'
// 导入组件的别名
import App from './App.vue'
// @ 表示 src 目录
import Test from '@/components/Test.vue'
const app = createApp(App)
// 注册全局组件
app.component('Test1', Test)
import router from './router'
app.use(router)
app.mount('#app')
// createApp(App).mount('#app')
路由传参
URL传参:一般用于页面跳转,将当前数据传递到新页面,例如详情页
params传参:
配置路由: {path: '/user/:id', component: about}
传递方式:<router-link :to="/user/6"></router-link>
传递后路径: /user/6
接受参数法:$route.params.id
query传参
配置路由: {path: '/user/', component: about}
传递方式:<router-link :to="{path: '/about',query:{id:6}}"></router-link>
传递后路径: /user?id=6
接受参数法:$route.query.id
路由守卫
正如其名,vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。简单来说,就是在路由跳转时候的一些钩子,当从一个页面跳转到另一个页面时,可以在跳转前、中、后做一些事情。
每个收尾方法接收参数:
- top: 即将要进入的目标,是一个路由对象
- from:当前导航正要离开的路由,也是一个路由对象
- next:可选,是一个方法,直接进入下一个路由
你可以使用 router.beforeEach 注册一个全局前置守卫,当一个导航触发时,就会异步执行这个回调函数。
const router = createRouter ({ .....
// 添加全局前置路由守卫
router.befoEach((to,from) ") {
// 这里执行具体操作
console.log(to)
console.log(from)
})
在网站开发中,使用导航守卫一个普遍需求:登录验证,,即在没有登录的情况下,访问任何页面都跳转到登录页面。
router.beforeEach((to, from, next) => {
// 添加全局前置导航守卫
// ...
console.log(to);
console.log(from);
if (to.path === "/login") {
return next();
}
const token = "" //模拟token,正常是从本地cookie或localstorage中获取
if (token) {
return next(); // 如果有token,则正常跳转访问
} else {
return next("/login"); // 如果没有token,跳转到登录页
}
});
完整代码
import { createRouter, createWebHistory } from "vue-router";
// 引入组件,一开是就会引入,即使不进入页面,也会加载组件
import Home from "@/views/Home.vue";
const routes = [
{
path: "/home",
name: "Home",
component: Home,
},
{
path: "/about",
name: "About",
// 引入组件,懒加载,只有在打开页面的时候才会加载
component: () => import("@/views/About.vue"),
},
{
path: "/login",
name: "Login",
// 引入组件,懒加载,只有在打开页面的时候才会加载
component: () => import("@/views/Login.vue"),
},
];
// 创建一个路由实例
const router = createRouter({
// 使用基于hash的路由历史模式
history: createWebHistory(),
// 定义路由配置数组
routes: routes,
// 配置路由模式
mode: "history",
});
router.beforeEach((to, from, next) => {
// 添加全局前置导航守卫
// ...
console.log(to);
console.log(from);
if (to.path === "/login") {
return next();
}
const token = ""
if (token) {
return next();
} else {
return next("/login");
}
});
// 导出路由实例以便在其他模块中使用
export default router;
Ant Design 使用
Element UI 它是由饿了么前端团队推出的基于 Vue 封装的 UI 组件库,提供PC 端组件,简化了常用组件的封装,降低开发难度。
Ant Design 是一套企业级 UI 设计语言和 React 组件库,提供了一套非常完整的组件化设计规范与组件化编码规范,能大幅提高了部分产品的设计研发效率及质量。
组件库文档:
安装
npm install ant-design-vue
全局注册
import { createApp } from 'vue'
import App from './App.vue'
// 引入antd和主题样式
import 'ant-design-vue/dist/reset.css';
import Antd from 'ant-design-vue'
// 全局引入antd图标
import * as Icons from '@ant-design/icons-vue';
const app = createApp(App)
// 全局引入antd图标, i是组件名。Icons[i]是具体的组件
for (const i in Icons) {
app.component(i, Icons[i])
}
import router from './router'
app.use(router)
// 全局引入antd
app.use(Antd)
app.mount('#app')
// createApp(App).mount('#app')
路由页面
import {createRouter,createWebHistory} from "vue-router";
const routes = [
{
path:"/btn",
component:( ) => import("@/view/test/btn.vue")
}
]
const router = createRouter({
history:createWebHistory(),
routes
})
export default router;
使用< router-view /> ,定义路由占位
// src/App.vue
<template>
<!-- 路由占位符 -->
<template>
<!-- 路由占位符-->
<router-view/>
</template>
<!--这里是全局的css效果-->
<style>
#app {
/* 100%的窗口宽和高 */
width: 100%;
height: 100%;
}
</style>
使用一个antd的按钮组件
<script setup>
</script>
<template>
<div style="margin: 20px;text-align: center;">
<a-space wrap>
<a-button type="primary">Primary Button</a-button>
<a-button>Default Button</a-button>
<a-button type="dashed">Dashed Button</a-button>
<a-button type="text">Text Button</a-button>
<a-button type="link">Link Button</a-button>
</a-space>
</div>
</template>
<style scoped>
.ant-btn {
margin-right: 8px;
margin-bottom: 20px;
}
</style>
浏览器打开localhost:8080/btn