vue 项目脚手架搭建
一、@vuew/cli搭建项目
npm run @vue/cli -g
vue create beauty-pc
二、安装sass
npm install node-sass@4.14.1 --save-dev
npm install sass-loader@8.0.2 --save-dev
三、安装vue-router
npm install vue-router
在main.js文件中 import router from './router/index.js' new Vue({ router, render: h => h(App), }).$mount('#app')
在router/index.js文件中 import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) // 路由注册
const Home = () => import('@/pages/index.vue')
const routes = [ { path: '/home', component: Home }, ]
export default new VueRouter({ mode: 'history', routes: [ ...routes, { path: '/*', redirect: '/home' } ] })
四、集成element-UI
npm i element-ui -S
五、安装vuex
npm install vuex --save
新建store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: { // state是存储中心,所有需要被共享或缓存的数据,都在这里定义 status: true, token: "7758258", },
getters: { // getters相当于组件的计算属性,它与state相关,当它所关系的state变量发生变化时,会自动重新计算 },
mutations: { // mutations是Vuex中专门用于更新state,同步任务 toChaneStatus(state, pyylod) { console.log(state) console.log(pyylod) } },
actions: {
toChang(store, payload) {
console.log(store)
console.log(payload)
store.commit("toChaneStatus", payload) } // actions是专门与后端api打交道的,异步任务;提交的是 mutation,而不是直接变更状态;可以包含任意异步操作。
},
modules: { //vuex分模块处理 }
})
export default store
main.js
import store from './store'
const app = new Vue({ store })
app.$mount()
六、vue项目的前期配置
一、新建vue项目,下载axios,并在main.js中导入axios
npm i axios -S
//main.js
import axios from "axios";
二、配置config文件中的代理地址
在项目config目录下的修改 index.js文件,这里是主要书写配置多个后台接口。关于代理可能出现的问题,可以查看我的另一篇文档VueCil代理本地proxytable报错的解析;
tips:如果报错服务器连接失败,是因为下面配置的代理地址是错误的,是我写的假的,需要替换成自己的服务器ip端口!!! error.message = ‘连接服务器失败’!
vue cil2旧版本的代理配置——config/index.js
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
// 后端请求地址代理,配置后testIp再之后的页面调用时就直接指代 http://197.82.15.15:8088
proxyTable: {
'/testIp': {
target: 'http://197.82.15.15:8088',
changeOrigin: true,
pathRewrite: {
'^/testIp': ''
}
},
'/elseIp': {
target: 'http://182.83.19.15:8080',
changeOrigin: true,
pathRewrite: {
'^/esleIp': ''
}
},
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
vuecil 3+ 新版本的代理配置–vue.config.js 文件
关于多代理配置:
devServer: {
overlay: { // 让浏览器 overlay 同时显示警告和错误
warnings: true,
errors: true
},
host: "localhost",
port: 8080, // 端口号
https: false, // https:{type:Boolean}
open: false, //配置后自动启动浏览器
hotOnly: true, // 热更新
// proxy: 'http://localhost:8080' // 配置跨域处理,只有一个代理
proxy: { //配置多个代理
"/testIp": {
target: "http://197.0.0.1:8088",
changeOrigin: true,
ws: true,//websocket支持
secure: false,
pathRewrite: {
"^/testIp": "/"
}
},
"/elseIp": {
target: "http://197.0.0.2:8088",
changeOrigin: true,
//ws: true,//websocket支持
secure: false,
pathRewrite: {
"^/elseIp": "/"
}
},
}
}
如果有多后台,就可以在api文件夹下另外新建一个elseApi.js ,书写当前ip下的接口请求。方法同上,只是 let resquest = “/elseIp/request/” 调用的时候把端口更改一下。
三、封装axios实例 —— request.js
在项目src目录下新建utils文件夹,然后在其中新建 request.js文件,这个文件是主要书写axios的封装过程。
/**** request.js ****/
// 导入axios
import axios from 'axios'
// 使用element-ui Message做消息提醒
import { Message} from 'element-ui';
//1. 创建新的axios实例,
const service = axios.create({
// 公共接口--这里注意后面会讲
baseURL: process.env.BASE_API,
// 超时时间 单位是ms,这里设置了3s的超时时间
timeout: 3 * 1000
})
// 2.请求拦截器
service.interceptors.request.use(config => {
//发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加
config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换
config.headers = {
'Content-Type':'application/x-www-form-urlencoded' //配置请求头
}
//注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie
const token = getCookie('名称');//这里取token之前,你肯定需要先拿到token,存一下
if(token){
config.params = {'token':token} //如果要求携带在参数中
config.headers.token= token; //如果要求携带在请求头中
}
return config
}, error => {
Promise.reject(error)
})
// 3.响应拦截器
service.interceptors.response.use(response => {
//接收到响应数据并成功后的一些共有的处理,关闭loading等
return response
}, error => {
/***** 接收到异常响应的处理开始 *****/
if (error && error.response) {
// 1.公共错误处理
// 2.根据响应码具体处理
switch (error.response.status) {
case 400:
error.message = '错误请求'
break;
case 401:
error.message = '未授权,请重新登录'
break;
case 403:
error.message = '拒绝访问'
break;
case 404:
error.message = '请求错误,未找到该资源'
window.location.href = "/NotFound"
break;
case 405:
error.message = '请求方法未允许'
break;
case 408:
error.message = '请求超时'
break;
case 500:
error.message = '服务器端出错'
break;
case 501:
error.message = '网络未实现'
break;
case 502:
error.message = '网络错误'
break;
case 503:
error.message = '服务不可用'
break;
case 504:
error.message = '网络超时'
break;
case 505:
error.message = 'http版本不支持该请求'
break;
default:
error.message = `连接错误${error.response.status}`
}
} else {
// 超时处理
if (JSON.stringify(error).includes('timeout')) {
Message.error('服务器响应超时,请刷新当前页')
}
error.message = '连接服务器失败'
}
Message.error(error.message)
/***** 处理结束 *****/
//如果不需要错误处理,以上的处理过程都可省略
return Promise.resolve(error.response)
})
//4.导入文件
export default service
config.data = JSON.stringify(config.data);
config.headers = { 'Content-Type':'application/x-www-form-urlencoded' }
const token = getCookie('名称')
if(token){
config.params = {'token':token} ;
config.headers.token= token;
}
上述的代码都是请求的配置项,非必须,也是分情况的,data/headers /params 这种本身的参数都有多种,和后台沟通,需要什么就配什么!
config.data = JSON.stringify(config.data);
为什么不用qs.stringify,因为我的后台想要的只是json类型的传参,而qs转换会转换成为键值对拼接的字符串形式。当然你们后台需要传递字符串类型参数,那就换成qs或者其他格式方式。
const token = getCookie('名称')
这是token的取值,在取之前你肯定需要发请求拿到token,然后setCookie存起来,而名称就是你存的token的名称,每个人的不一样;
config.headers = { 'Content-Type':'application/x-www-form-urlencoded' }
请求头内容的配置,也是不同的,application/x-www-form-urlencoded
:form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式),你可以根据实际情况去配置自己需要的;
如果最终配完成后,报错连接服务器失败,那是正常的,因为示例配置的服务器地址http://197.0.0.2:8088是假地址,需要替换成自己服务器;
以上
我已经举了很清晰的例子,写代码的过程是自己动脑去搭建工程的,希望能看到我文章的各位,善于搜索,善于思考,善于总结;
当然我很喜欢帮大家解决问题,但是相关的基础问题,还是建议自己去学习掌握。
四、封装请求——http.js
在项目src目录下的utils文件夹中新建 http.js文件,这个文件是主要书写几种请求的封装过程。
/**** http.js ****/
// 导入封装好的axios实例
import request from './request'
const http ={
/**
* methods: 请求
* @param url 请求地址
* @param params 请求参数
*/
get(url,params){
const config = {
method: 'get',
url:url
}
if(params) config.params = params
return request(config)
},
post(url,params){
const config = {
method: 'post',
url:url
}
if(params) config.data = params
return request(config)
},
put(url,params){
const config = {
method: 'put',
url:url
}
if(params) config.params = params
return request(config)
},
delete(url,params){
const config = {
method: 'delete',
url:url
}
if(params) config.params = params
return request(config)
}
}
//导出
export default http
五、正式封装API,用于发送请求——api.js
在项目src目录下新建api文件夹,然后在其中新建 api.js文件,这个文件是主要书写API的封装过程。
写法一:适合分类导出
import http from '../utils/http'
//
/**
* @parms resquest 请求地址 例如:http://197.82.15.15:8088/request/...
* @param '/testIp'代表vue-cil中config,index.js中配置的代理
*/
let resquest = "/testIp/request/"
// get请求
export function getListAPI(params){
return http.get(`${resquest}/getList.json`,params)
}
// post请求
export function postFormAPI(params){
return http.post(`${resquest}/postForm.json`,params)
}
// put 请求
export function putSomeAPI(params){
return http.put(`${resquest}/putSome.json`,params)
}
// delete 请求
export function deleteListAPI(params){
return http.delete(`${resquest}/deleteList.json`,params)
}写法二:使用全部导出
import http from '../utils/http'
//
/**
* @parms resquest 请求地址 例如:http://197.82.15.15:8088/request/...
* @param '/testIp'代表vue-cil中config,index.js中配置的代理
*/
let resquest = "/testIp/request/"
// get请求
export default{
getListAPI(params){
return http.get(`${resquest}/getList.json`,params)
},
postFormAPI(params){
return http.post(`${resquest}/postForm.json`,params)
}
}
注意:一个项目中如果后台请求不是同一个ip,而是多个ip的时候,可以在api文件夹下建立多个js,用来调用请求。
我们看下之前遗留的一个问题:
// 创建新的axios实例,
const service = axios.create({
baseURL: process.env.BASE_API,
timeout: 3 * 1000
})
在之前封装公共接口的baseUrl时候,用了webpack中的全局变量process.env.BASE_API,而不是直接写死ip,也是为了适应多个后台或者开发的时候的api地址和发布的时候的api地址不一样这种情况。
以上 关于配置环境 和接口 基本搭建完毕,下面看一下调用:
六、如何在vue文件中调用
方法一:用到哪个api 就调用哪个接口——适用于上文接口分类导出;
import {getListAPI,postFormAPI, putSomeAPI, deleteListAPI} from '@/api/api'
methods: {
//promise调用,链式调用, getList()括号内只接受参数;
// get不传参
getList() {
getListAPI().then(res => console.log(res)).catch(err => console.log(err))
},
//post传参
postForm(formData) {
let data = formData
postFormAPI(data).then(res => console.log(res)).catch(err => console.log(err))
},
//async await同步调用
async postForm(formData) {
const postRes = await postFormAPI(formData)
const putRes = await putSomeAPI({data: 'putTest'})
const deleteRes = await deleteListAPI(formData.name)
// 数据处理
console.log(postRes);
console.log(putRes);
console.log(deleteRes);
},
}
方法二 :把api全部导入,然后用哪个调用哪个api——适用于全部导出
import api from '@/api/api'
methods: {
getList() {
api.getListAPI(data).then(res => {
//数据处理
}).catch(err => console.log(err))
}
}
Vue + Element UI的主题切换实现
插件的安装
npm i element-theme -g
npm i element-theme-chalk -D
打开官方文档, element-UI自定义主题
放置文件
创建目录 ,在根目录下面创建theme文件夹;
拖拽文件,将已经下载好的文件放到一个文件夹中,比如命名 gray ,拖到theme文件夹中;
在这里插入图片描述
使用gulp实现切换
安装插件
npm install gulp
npm install gulp-clean-css
npm install gulp-css-wrap
创建文件 (gulpfile.js)
var path = require('path')
var gulp = require('gulp')
var cleanCSS = require('gulp-clean-css')
var cssWrap = require('gulp-css-wrap')
gulp.task('css-wrap', function () {
return gulp.src(path.resolve('./theme/gray/index.css'))
.pipe(cssWrap({
selector: '.gray' /* 填写对应主题的class名 */
}))
.pipe(cleanCSS())
.pipe(gulp.dest('src/assets/css/theme/gray')) /* 存放的目录 */
})
// 控制台中输入命令
> gulp css-wrap
//使用vuex进行切换主题
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
tcolor: 'pure'// 默认为pure
},
mutations: {
// 更新主题颜色
setTColor(state, color) {
this.state.themecolor = color
}
}
})
export default store
main.js, 添加下面的代码
import store from './store/index.js'
import './assets/css/theme/pure/index.css'
加入工具src/utils文件夹, 创建index.js文件
export function toggleClass(element, className) {
if (!element || !className) {
return
}
element.className = className
创建一个组件,用来切换颜色
<template>
<div>
<el-dropdown @command="handleCommand">
<div style="color: white; font-size: 22px;margin-right: 20px; cursor: pointer;">
主题
</div>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item command="gray">灰色</el-dropdown-item>
<el-dropdown-item command="pure">紫色</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-button type="primary">查看主题是否变色</el-button>
</div>
</template>
<script>
import { toggleClass } from '../utils/index'
export default {
computed: {
themecolor: {
get () {
return this.$store.state.tcolor
}
}
},
mounted() {
toggleClass(document.body, this.tcolor)
},
methods: {
handleCommand(command) {
if (command === 'gray') {
this.$store.commit('setTColor', command)
toggleClass(document.body, this.tcolor)
} else {
this.$store.commit('setTColor', command)
toggleClass(document.body, this.tcolor)
}
}
}
}