背景
作为一个三年左右的程序员,时常是焦虑的,总是感觉会的不多,想着后面的路到底怎么走?要不要继续接着往下走!质疑的声音就慢慢出现在自己的耳边,但是我不能放弃,走到今天挺不容易的,面对自己对自己的质疑,要坦然面对,积极克服,失败者才会放弃。我不是聪明的大多数,我想做勤奋的小部分。所以今年就萌生了好好写文章来记录知识点的想法,毕竟现在的学习成本太高,忘记了重新再去学习,精力、时间都是不允许,文章记录下来可以时不时巩固一下。这可能不是最好的方式,但是我目前认为最好的方式,我不会放弃,我一直在路上。致敬每一位为梦想坚持的人,平凡人是大多数,不要总被外部环境影响。加油!!! :)
全局安装
// 基于当前最新的@vue/cli,全局安装快速原型开发。
cnpm install -g @vue/cli
创建项目
vue create vue-project-template
//或者
vue ui //使用界面化构建,vuex、vue-router都会配置好
安装vue-router
npm install vue-router -S
- 新建router文件夹 index.js文件,并注入根节点
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: () => import("../views/Home.vue"),
},
{
path: "/about",
name: "About",
component: () => import("../views/About.vue"),
},
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
});
export default router;
//vue-cli@2.0版本
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
//vue-cli@3.0以上版本
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
createApp(App)
.use(router)
.mount("#app");
// App.vue 路由视图
<template>
<div id="app">
<router-view/>
</div>
</template>
安装vuex
npm install vuex -S
- 新建store文件夹 index.js文件,并注入根节点
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App)
}).$mount('#app')
总结:如果项目够大,我们可以分模块去管理,详情
安装axios
npm install axios -S
- 封装请求
import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
// axios中请求配置有baseURL选项,表示请求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
// 超时
timeout: 10000
})
// request拦截器
service.interceptors.request.use(
config => {
if (getToken()) {
config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
}
return config
},
error => {
console.log(error)
Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(res => {
const code = res.data.code
if (code === 401) {
MessageBox.confirm(
'登录状态已过期,您可以继续留在该页面,或者重新登录',
'系统提示',
{
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.reload() // 为了重新实例化vue-router对象 避免bug
})
})
} else if (code !== 200) {
Notification.error({
title: res.data.msg
})
return Promise.reject('error')
} else {
return res.data
}
},
error => {
console.log('err' + error)
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
- 根据功能模块创建请求
import service from "../../src/utils/request";
/**
* 登录接口
*/
export function Login(data) {
return service.request({
url: "/login/",
method: "POST",
data,
});
- 组件调用
import { Login } from "../../api/account";
onFinish = (values) => {
Login(values)
.then((res) => {
message.success("登录成功");
console.log(res);
})
.catch((err) => {
console.log(err);
});
console.log("Received values of form: ", values);
};
总结:如果您有前端跨域的需求,请移步
预处理器Less
npm install less less-loader --save-dev
- 按需调用
// 单文件使用
<style scoped lang="less">
@import "../../../style/config.less";//引入公共样式
@import "../../../style/styles.less";
.upload-file-container {
display: flex;
align-items: center;
.upload-bt {
width: 80px;
height: 30px;
border-radius: 6px;
border: 1px solid @defaultBlueClick;//使用公共样式
.flexCenter();
color: @defaultBlueClick;
cursor: pointer;
i {
font-size: 20px;
margin-right: 4px;
position: relative;
top: 1px;
}
}
}
</style>
// 公共样式库
@leftNavBarWidth: 210px; // 侧边导航栏宽度
@leftCollapseBarWidth: 70px; // 侧边栏收起后高度
@leftCollapseBarHoverColor: rgba(55, 71, 96, 1); // 侧边栏一级按钮hover颜色
@leftNavBarBgColor: rgba(44, 59, 81, 1); // 侧边导航栏颜色
@logoHeight: 210px; // 左上角logo栏的高度
@navActiveBgColor: rgba(55, 71, 96, 1); // 侧边导航栏打开后的背景色
//使用
border: 1px solid @defaultBlueClick;//使用公共样式
========================================================
//公共样式库
.flexCenter() {
display: flex;
justify-content: center;
align-items: center;
}
.oneLineWord() {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
//使用
.el-tabs__nav-scroll {
.flexCenter()
}
- 全局变量
1.首先需要安装style-resources-loader插件
npm install sass-resources-loader --save-dev
2.在vue.config.js中配置
// 第三方插件配置
pluginOptions: {
'style-resources-loader': {
preProcessor: 'less',
patterns: [
// 全局变量路径,不能使用路径别名
path.resolve(__dirname, './src/assets/css/rainbow-variables.less')
]
}
},
使用class
- 在utils文件下新建data.js用于存放方法,index.js文件用于分模块导出
//data.js
class Activity {
// 性别
sexOptions() {
return [
{ label: "男", value: "male" },
{ label: "女", value: "female" },
];
}
getSexLabelByValue(value) {
let row = this.sexOptions().filter((d) => d.value === value);
if (row.length !== 1) return false;
return row[0].label;
}
}
class system {}
const Data = {
activity: new Activity(),
system: new system(),
};
export default Data;
//index.js
import data from "./data";
export default {
data,
};
// 全局引用 main.js
import $utils from "./utils";
Vue.prototype.$utils = $utils;
//组件中使用
this.$utils.data.activity.getSexLabelByValue("male")
配置vue-config.js
module.exports = {
publicPath:
process.env.NODE_ENV === "production" ? "/production-sub-path/" : "/", //部署应用包时的基本 URL
outputDir: "dist", //当运行 vue-cli-service build 时生成的生产环境构建文件的目录
assetsDir: "", //放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录。
indexPath: "index.html", //指定生成的 index.html 的输出路径 (相对于 outputDir)。也可以是一个绝对路径。
filenameHashing: true, //默认情况下,生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存。然而,这也要求 index 的 HTML 是被 Vue CLI 自动生成的。如果你无法使用 Vue CLI 生成的 index HTML,你可以通过将这个选项设为 false 来关闭文件名哈希。
pages: {
index: {
//page入口文件
entry: "src/main.js",
//模板文件
template: "public/index.html",
//在dist/index.html的输出
filename: "index.html",
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: "Index Page",
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ["chunk-vendors", "chunk-common", "index"],
// 简写格式
// 模板文件默认是 `public/subpage.html`
// 如果不存在,就是 `public/index.html`.
// 输出文件默认是 `subpage.html`.
subpage: "src/main.js" /*注意这个是*/,
},
},
// 是否在保存的时候使用 `eslint-loader` 进行检查。
// 有效的值:`ture` | `false` | `"error"`
// 当设置为 `"error"` 时,检查出的错误会触发编译失败。
lintOnSave: process.env.NODE_ENV !== "production", //false
//使用带有浏览器内编译器的完整构建版本
runtimeCompiler: false,
//默认情况下 babel-loader 会忽略所有 node_modules 中的文件。如果你想要通过 Babel 显式转译一个依赖,可以在这个选项中列出来。
transpileDependencies: [],
//如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
productionSourceMap: false,
// 调整内部的 webpack 配置。
// 查阅 https://github.com/vuejs/vue-docs-zh-cn/blob/master/vue-cli/webpack.md
chainWebpack: () => {},
configureWebpack: () => {},
css: {
//是否将组件中的 CSS 提取至一个独立的 CSS 文件中 (而不是动态注入到 JavaScript 中的 inline 代码)。
//生产环境下是 true,开发环境下是 false
extract: false,
//是否为 CSS 开启 source map。设置为 true 之后可能会影响构建的性能。
sourceMap: false,
// 为预处理器的 loader 传递自定义选项。比如传递给
// sass-loader 时,使用 `{ sass: { ... } }`。
loaderOptions: {},
// 为所有的 CSS 及其预处理文件开启 CSS Modules。
// 这个选项不会影响 `*.vue` 文件。
modules: false,
},
// 配置 webpack-dev-server 行为。
devServer: {
open: process.platform === "darwin",//配置后自动启动浏览器
host: "0.0.0.0",
port: 8080,
https: false,
hotOnly: false,//热更新
// 查阅 https://github.com/vuejs/vue-docs-zh-cn/blob/master/vue-cli/cli-service.md#配置代理
proxy: {
"/admin": {
target: "http://huangshan.jsxhfh.com/admin",
changeOrigin: true,
pathRewrite: {
"^/admin": "",
},
},
},
// 三方插件的选项
pluginOptions: {
// ...
},
},
};
github地址 望批评指教!!!