一. 使用 vue-cli 搭建项目
安装vue/cli
1.安装vue/cli ,执行下面的命令安装或是升级
npm i -g @vue/cli
安装vue/cli 报错解决方案
如果安装报错如下
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): EPERM: operation not permitted, rmdir'D:\Devlop\nodejs\node_global\node_modules\@vue\cli'npm ERR! code EEXIST
npm ERR! path D:\Devlop\nodejs\node_global\node_modules\@vue\cli\bin\vue.js
npm ERR! dest D:\Devlop\nodejs\node_global\vue.cmd
npm ERR! EEXIST: file already exists, cmd shim 'D:\Devlop\nodejs\node_global\node_modules\@vue\cli\bin\vue.js' ->'D:\Devlop\nodejs\node_global\vue.cmd'npm ERR! File exists: D:\Devlop\nodejs\node_global\vue.cmd
npm ERR! Remove the existing file and try again, or run npmnpm ERR! with --force to overwrite files recklessly.
npm ERR! A complete log of this run can be found in:
npm ERR! D:\Devlop\nodejs\node_cache\_logs\2023-04-13T02_13_31_038Z-debug.log
查看vue版本
vue -V
,主要原因是安装vue的版本过低。
D:\study_html\vueApp>vue -V
2.9.6
输入以下命令 ,可以强制覆盖以前旧版本的vue-cli脚手架。
npminstall -g @vue/cli --force
执行完,看到
+ @vue/[email protected]
安装成功。
+ @vue/[email protected]
added 842 packages from 491 contributors in84.507s
vue creat创建项目
- 在命令行输入以下命令创建Vue项目
vue create 项目名称
当使用vue create 命令创建项目失败, 发现报错如下:
D:\study_html\vueApp>vue create demoApp
Invalid project name: "demoApp"
Warning: name can no longer contain capital letters
D:\study_html\vueApp>vue create myApp
Invalid project name: "myApp"
Warning: name can no longer contain capital letters
vue命令无法创建命名包含大写字母的项目。所以,在命令行创建vue项目时,要用小写英文字母来命名项目,也可以用 vue ui 可视化界面来创建项目。
项目配置操作步骤说明
① 正确创建如下,输入 y
D:\study_html\vueApp>vue create demo-app
? Your connection to the default yarn registry seems to be slow.
Use https://registry.npmmirror.com for faster installation? Yes
② 选择第二种,手动选择特性,支持更多自定义选项
- Default 表示使用默认配置,默认勾选babel、eslint ,回车之后直接进入装包
- Manually 自定义勾选特性配置,选择完毕后,才能进入装包
Vue CLI v5.0.8
? Please pick a preset:
Default ([Vue 3] babel, eslint)
Default ([Vue 2] babel, eslint)> Manually select features
③ 自定义选择要安装的插件。( 按空格是选择勾还是不勾,按回车是代表确认。)
babel: 把ES6语法可以转换成ES5语法的插件
Router:vue-router,路由,因为项目要用到路由跳转所以勾上
Vuex:我们项目也会用,但是还没学,所以先不勾,学的时候再来下载
CSS Pre-processors: css的预处理,可以选择less和sass,因为我们这个项目样式用less,所以悬赏
注意:按空格是选择勾还是不勾,按回车是代表确认
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection, and
<enter> to proceed)(*) Babel
() TypeScript
() Progressive Web App (PWA) Support
(*) Router
>(*) Vuex
(*) CSS Pre-processors
(*) Linter / Formatter
() Unit Testing
() E2E Testing
④ 选择vue的版本 ,选择2.x项目
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with
3.x
>2.x
⑤ 是否使用history模式的路由,不需要,输入n (我们之前用的路由都是hash模式)
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback in production)(Y/n)
⑥选择css预处理语言 ,勾选 Less
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default):
Sass/SCSS (with dart-sass)> Less
Stylus
⑦ 选择代码格式校验使用哪种校验规范,选择第三种,回车
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less
? Pick a linter / formatter config:
ESLint with error prevention only
ESLint + Airbnb config
> ESLint + Standard config
ESLint + Prettier
⑧ 选择什么情况下触发代码校验,按空格表示勾选,全选然后回车
- Lint on save 当修改报错文件时触发
- Lint and fix on commit 当执行git committ提交时
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less
? Pick a linter / formatter config: Standard
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to
proceed)>(*) Lint on save
(*) Lint and fix on commit
⑨对应Babel, ESLint等配置文件是,这里选择独立的,勾选第一个
- In dedicated config files 生成保存到独立的配置文件中
- In package.json 把插件的配置信息和package.json文件写在一起
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less
? Pick a linter / formatter config: Standard
? Pick additional lint features: Lint on save, Lint and fix on commit
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)> In dedicated config files
In package.json
⑩选择 你要不要保存当前的设置,方便下一次快速使用。如果你要保存输入y,不需要保存输入n。这里我选择n.
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less
? Pick a linter / formatter config: Standard
? Pick additional lint features: Lint on save, Lint and fix on commit
? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? (y/N)
①① 选择哪种方式安装依赖,我选择npm
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less
? Pick a linter / formatter config: Standard
? Pick additional lint features: Lint on save, Lint and fix on commit
? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? No
? Pick the package manager to use when installing dependencies:
Use Yarn
> Use NPM
最后,安装成功后,提示
added 216 packages from 110 contributors in27.327s
152 packages are looking for funding
run `npm fund`for details
⚓ Running completion hooks...
� Generating README.md...
� Successfully created project demo-app.
� Get started with the following commands:
$ cd demo-app
$ npm run serve
运行测试
3.启动项目 ,运行项目
npm run serve
① 进入所在项目路径
D:\study_html\vueApp>cd demo-app
② 执行命令,查看项目启动成功
D:\study_html\vueApp\demo-app>npm run serve
> [email protected] serve D:\study_html\vueApp\demo-app
> vue-cli-service serve
INFO Starting development server...
DONE Compiled successfully in 5229ms 上午11:00:41
App running at:
- Local: http://localhost:8080/
- Network: http://10.12.48.22:8080/
Note that the development build is not optimized.
To create a production build, run npm run build.
二、调整目录结构
(1) 删除 App.vue 里不需要的代码,就留一个根标签
<template>
<div id="app">
<!-- 路由的出口 -->
<router-view />
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style lang="less">
</style>
(2) 删除 Router 文件夹里的 index.js,默认的路由规则还组件导入
import Vue from'vue'import VueRouter from'vue-router'
Vue.use(VueRouter)// 路由表const routes =[]const router =newVueRouter({
routes
})exportdefault router
(3) 来到 views 文件夹 和 components 文件夹里删除默认的几个 vue文件
(4) 来到 assets 文件夹里面,删除默认的logo图片,放入我们自己的图片
(5) 在 src 下,新建 utils文件夹,这里存放工具类
(6) 在 src 下,新建 styles 文件夹,在这里面是放我们样式的地方
我们在这新建一个 base.less 文件,写一些基础通用的样式,然后来到 main.js 导入这个样式
import Vue from'vue'import App from'./App.vue'import router from'./router'import store from'./store'// 加载全局样式import'./styles/index.less'
Vue.config.productionTip =falsenewVue({
router,
store,render:h=>h(App)}).$mount('#app')
三、导入图标素材
iconfont说明
介绍: iconfont-国内功能很强大且图标内容很丰富的矢量图标库,提供矢量图标下载、在线存储、格式转换等功能。
导入步骤说明
(1) 登录 iconfont网站,在我的项目中 使用导出的 SVG 图标上传到 iconfont ,下载对应的css 。
(2) 在styles文件夹中新增icon.css文件。iconfont 下载的css 复制到icon.css
// 全局样式
@font-face{font-family:'toutiao';src:url('//at.alicdn.com/t/font_1715884_c380afk5f66.eot?t=1585203719136');/* IE9 */src:url('//at.alicdn.com/t/font_1715884_c380afk5f66.eot?t=1585203719136#iefix')format('embedded-opentype'),/* IE6-IE8 */url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAA64AAsAAAAAGWQAAA5pAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCFCAqiOJsEATYCJANUCywABCAFhGEHgWsbvRQzkpFWJtl/dcAbxhtdSaZIq20EveGtsMBUwuRMnkCPhWwVc8NzsR8LFiz4+76N+YODfT+UEp5qjvft3eV+sgH+gDweqEDCMCu0Ve34atXx7CpM5p/f5t/Ho+oh2BtpJVYCRmEiRgRGrRlGL0tdVfHPMBawiOTg1/ncykebmdWHRsy65Io6gkTUaSDJt5kWsduNrLH8uyqighRAwDbV0sqyMGV0G7N+2+uOQRQflnwg2Ulgwpgi85f1f2upvQmQujvhRoQcCRerZvY2yf7Zf/DDE+YJsEoRVF+Na4XaCZeAXE5XuBptCzWnHMbdR8SkOjQa2DZus4KslTIk+qveHwIoo5bJweeFG+BxmEqw4Em8fxN8ph4niAhhwjOu61S+wR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6jBFlYsNAZxusEt4YmdzV1vGcql/1Lj4ufQAHYf4xbRQSGp3BZLE5PLxcPv5IRqPMrMYOJZA84fLU+AqAftSHQlKEjjbmRSw7lqDRBJGaiFPEU9mV232bgJXdQhYuL6HB6GGSQ+woOBo9w5X8fgG0+uBFYx+PTNMnwX2KFdHR19VmhT4+c4jnRRbNM+nkAB8xqVutAAAA')format('woff2'),url('//at.alicdn.com/t/font_1715884_c380afk5f66.woff?t=1585203719136')format('woff'),url('//at.alicdn.com/t/font_1715884_c380afk5f66.ttf?t=1585203719136')format('truetype'),/* chrome, firefox, opera, Safari, Android, iOS 4.2+ */url('//at.alicdn.com/t/font_1715884_c380afk5f66.svg?t=1585203719136#toutiao')format('svg');/* iOS 4.1- */}.toutiao{font-family:'toutiao'!important;font-size: 16px;font-style: normal;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;}.toutiao-shouye:before{content:'\e608';}.toutiao-yanzhengma:before{content:'\e609';}.toutiao-sousuo:before{content:'\e60a';}.toutiao-dianzan:before{content:'\e60b';}.toutiao-shanchu:before{content:'\e60c';}.toutiao-shipin:before{content:'\e60d';}.toutiao-dianzan1:before{content:'\e60e';}.toutiao-yuedu:before{content:'\e60f';}.toutiao-wode:before{content:'\e610';}.toutiao-zuojiantou:before{content:'\e611';}.toutiao-zuopin:before{content:'\e612';}.toutiao-shoucang:before{content:'\e613';}.toutiao-wenda:before{content:'\e614';}.toutiao-guanbi:before{content:'\e600';}.toutiao-pinglun:before{content:'\e601';}.toutiao-lishi:before{content:'\e602';}.toutiao-gengduo:before{content:'\e603';}.toutiao-shouji:before{content:'\e604';}.toutiao-wuwangluo:before{content:'\e605';}.toutiao-youjiantou:before{content:'\e606';}.toutiao-fenxiang:before{content:'\e607';}
(3)全局样式配置 index.less中导入icon.less
// 全局样式// 加载图标样式
@import'./icon.less';
(4) 测试,在App.vue中测试图标是否正常
<template><divid="app"><!-- 路由的出口 --><router-view/><div><iclass="toutiao toutiao-dianzan"></i></div></div></template><script>exportdefault{name:'App'}</script><stylelang="less"></style>
(5) 导入项目中所需对应图片资源到assets目录中,用于页面布局
(6) 替换public中的favicon.ico图标 ,使用自己的
四、引入Vant组件库
vant官网
vant2中文文档地址: https://vant-contrib.gitee.io/vant/v2/#/zh-CN/
整合vant:通过 npm 安装
在现有项目中使用 Vant 时,可以通过
npm
或
yarn
进行安装:
# Vue 3 项目,安装最新版 Vant:npm i vant -S
# Vue 2 项目,安装 Vant 2:npm i vant@latest-v2 -S
vant导入的说明
- 全局导入:
- 优点:使用方便,只要在main.js里导入好vant,那么后面在这个项目中的任意位置,都可以直接使用vant的组件- 缺点:不管用到还是没用到的东西都会导入到项目里,就导致项目会变的比较大- 如果项目要考虑性能优化,那么一定不要用全局导入的方式
- 按需导入:
- 优点:按需导入,那么到时候项目打包时会根据你用到的东西,单独把用到的东西拿出来打包,就不会造成体积上的浪费,网页打开的速度就会相对快一点- 缺点:不利于开发,开发写起来比较麻烦
自动按需引入组件 (推荐)
- 先下载一个插件 :babel-plugin-import
- babel-plugin-import 是一款 babel 插件,它会在编译过程中将 import 的写法自动转换为按需引入的方式。
# 安装插件npm i babel-plugin-import -D
- 然后来到项目根目录,找到 babel.config.js 这个文件,添加如下配置
// 在.babelrc 中添加配置// 注意:webpack 1 无需设置 libraryDirectory{"plugins":[["import",{"libraryName":"vant","libraryDirectory":"es","style":true}]]}// 对于使用 babel7 的用户,可以在 babel.config.js 中配置
module.exports ={plugins:[['import',{libraryName:'vant',libraryDirectory:'es',style:true},'vant']]};
接着你可以在代码中直接引入 Vant 组件, 插件会自动将代码转化为方式二中的按需引入形式
import{ Button }from'vant';
- 来到 src 目录,新建一个文件夹叫 utils ,这个文件夹代表工具的意思,以后把开发中需要用到的 工具 都放到这个文件夹里,比如 vant 也是工具,所以放到这个文件夹里
- 因此在 utils 文件夹里,再新建 vant.js,然后把自动按需导入vant的代码写到这里面即可
- 然后来到 main.js 里导入这个 vant.js 即可
- 最后调试完成,记得把多余的测试代码和文件删掉
vant测试导入步骤流程
(1)通过 npm 安装 Vant ,执行
npm i vant@latest-v2 -S
,这里项目是vue2.x版本,安装vant2即可 ,安装成功。
PS D:\study_html\vueApp\demo-app>npm i vant@latest-v2 -S
npm WARN @vue/[email protected] requires a peer of eslint-plugin-vue@^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"}(current: {"os":"win32","arch":"x64"})
+ [email protected]
added 4 packages from 3 contributors in6.158s
152 packages are looking for funding
run `npm fund`for details
(2)在main.js中全局导入: 支持一次性导入所有组件,引入所有组件会增加代码包体积,因此不推荐这种做法。
import Vue from 'vue';
import Vant from 'vant';
import 'vant/lib/index.css';
Vue.use(Vant);
(3) 测试效果,在App.vue中使用vant组件,验证是否有效。
<template><divid="app"><!-- 路由的出口 --><router-view/><div><iclass="toutiao toutiao-dianzan"></i></div><div><van-buttontype="primary">主要按钮</van-button><van-buttontype="info">信息按钮</van-button><van-buttontype="default">默认按钮</van-button><van-buttontype="warning">警告按钮</van-button><van-buttontype="danger">危险按钮</van-button></div></div></template><script>exportdefault{name:'App'}</script><stylelang="less"></style>
注意:安装vant后运行报错
这里错误去安装了vant最新的版本,导致不兼容
PS D:\study_html\vueApp\demo-app>npm i vant -S
npm WARN @vue/[email protected] requires a peer of eslint-plugin-vue@^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of vue@^3.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN @vant/[email protected] requires a peer of vue@^3.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"}(current: {"os":"win32","arch":"x64"})
+ [email protected]
added 3 packages from 1 contributor in11.659s
152 packages are looking for funding
run `npm fund`for details
安装了vant 3以上版本,在vue2引入vant组件库不生效,报错:
ERROR in ./node_modules/vant/es/uploader/UploaderPreviewItem.mjs 72:28-40
export'createVNode'(imported as '_createVNode') was not found in'vue'(possible exports: EffectScope, computed, customRef, default, defineAsyncComponent, defineComponent, del, effectScope, getCurrentInstance, getCurrentScope, h, inject, isProxy, isReactive, isReadonly, isRef, isShallow, markRaw, mergeDefaults, nextTick, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onServerPrefetch, onUnmounted, onUpdated, provide, proxyRefs, reactive, readonly, ref, set, shallowReactive, shallowReadonly, shallowRef, toRaw, toRef, toRefs, triggerRef, unref, useAttrs, useCssModule, useCssVars, useListeners, useSlots, version, watch, watchEffect, watchPostEffect, watchSyncEffect)
@ ./node_modules/vant/es/uploader/Uploader.mjs 10:0-60 178:26-45
@ ./node_modules/vant/es/uploader/index.mjs 2:0-39 3:29-38 5:0-47 6:0-61
@ ./node_modules/vant/es/index.mjs 94:0-48 97:963-971 200:0-37 200:0-37
@ ./src/main.js 10:0-24 12:8-12
执行
npm uninstall vant
卸载后重装 vant2即可 。
五、移动端REM适配
Rem 布局适配
Vant中的样式默认使用
px
作为单位。如果需要使用
rem
单位进行适配,推荐使用以下两个工具:
- postcss-pxtorem 是一款 PostCSS 插件,用于将 px 单位转化为 rem 单位
- lib-flexible 用于设置 rem 基准值
下面我们分别将这两个工具配置到项目中完成rem适配。
回顾rem单位
- rem是一种可以变换的单位,它是根据 html标签 的 font-size 的大小而变化的
- 具体是 html 的 font-size 是多少,那么 1rem就是多少 像素
- 例如:我给 html 的 font-size 如果设置的是 28。那么 1rem 就是 28px
flexible 插件介绍
github
- 因为 rem 这个单位是要根据 html 的字号的变化而变化,那么html字号要如何才能变换呢?
- 要么我们自己写媒体查询,根据不同的屏幕宽度给html设置不同的字号,但是这样就比较麻烦,因为移动端的屏幕特别多,要自己写媒体查询,就累到吐血,所以可以用别人写好的插件,自动根据屏幕大小来设置html的字号
- flexible 就是一种能根据屏幕自动设置html字号的插件
- 特点:会把屏幕宽度分成10等份,所以html的字号就是屏幕宽度的1/10,例如375宽的屏幕,html字号是37.5,所以如果10rem就会让它占满屏幕
使用lib-flexible动态设置·rem基准值(html标签的字体大小):
(1)npm 安装
#yarn add amfe-flexiblenpm i amfe-flexible
(2) 在
main.js
中加载执行该模块
// 导入flexible
import'amfe-flexible'
(3) 测试,在浏览器中切换不同的手机设备尺寸,查看html标签
font-size
的变化
postcss介绍
- 是一个 后处理css插件:在项目写完后打包的时候对我们写的css进行处理
- 它有各种各样的插件:比如说有 autoprefix 就是可以在项目写完后打包的时候,自动把你写的有兼容问题的代码,前面加上浏览器的标识前缀- transfrom:在代码中就直接写transfrom,只要你用 postcss-autoprefix 这个插件,它就可以在打包时自动帮你去生成 -webkit-transform: 这种形式 -moz-transform- postcss-pxtorem:
- 我们移动端单位用rem,美工给我们出的图单位用的是像素也就是px,所以如果我们要用rem单位就得自己把美工的像素计算成rem,这样做很麻烦- 这款插件就是允许我们继续用px作为单位,通过这个插件,它会在打包时自动的把px改成rem
- less、sass,叫 预处理css,是在页面一打开时就进行处理,比如说把less的变量和语法再解析成普通的css语法
使用postcss-pxtorem将px转化为rem
(1) npm 安装
#yarn add postcss-pxtorem#-D是 --save-dev的缩写npminstall postcss-pxtorem -D
(2) 在项目根目录中创建
.postcssrc.js
文件 下面提供了一份基本的 PostCSS 示例配置,可以在此配置的基础上根据项目需求进行修改。
module.exports ={plugins:{'autoprefixer':{browsers:['Android >= 4.0','iOS >= 8']},'postcss-pxtorem':{rootValue:37.5,propList:['*']}}}
(3) 配置完成,重启服务。刷新浏览器,审查元素的样式查看是否将 px转化为rem.
关于
.postcssrc.js
配置文件
.postcssrc.js
是 PostCSS 的配置文件。- 目前 PostCSS 已经有 200 多个功能各异的插件。开发人员也可以根据项目的需要,开发出自己的 PostCSS 插件。PostCSS 一般不单独使用,而是与已有的构建工具进行集成。
- Vue CLI 默认集成了 PostCSS,并且默认开启了 autoprefixer 插件。
- Vue CLI 内部使用了 PostCSS。
- 你可以通过 .postcssrc 或任何 postcss-load-config 支持的配置源来配置 PostCSS。也可以通过 vue.config.js 中的 css.loaderOptions.postcss 配置 postcss-loader。
- 我们默认开启了 autoprefixer。如果要配置目标浏览器,可使用 package.json 的 browserslist 字段。
六、封装请求模块
和之前项目一样,这里我们还是使用 axios 作为我们项目中的请求库,为了方便使用,我们把它封装为一个请求模块,在需要的时候直接加载即可。
1、安装 axios
npm i axios
2、创建 src/utils/request.js
/**
* 封装 axios 请求模块
*/import axios from"axios"const request = axios.create({baseURL:"http://localhost:8080/"// 基础路径})exportdefault request
3、如何使用
方式一(简单方便,但是不利于接口维护):我们可以把请求对象挂载到 Vue.prototype 原型对象中,然后在组件中通过 this.xxx 直接访问
方式二(推荐):我们把每一个请求都封装成每个独立的功能函数,在需要的时候加载调用,这种做法更便于接口的管理和维护
版权归原作者 我有满天星辰 所有, 如有侵权,请联系我们删除。