文章目录
关键词
- @vue/cli4, vant, rem, svg, axios
参考链接
一. 使用vue/cli4
-
全局安装@vue/cli最新版本
yarn add -g @vue/cli
或者npm install @vue/cli -g
-
查看安装的vue/cli版本
vue --version
-
创建vue项目
vue create hello-world
-
创建项目时候让选择,默认or手动,一般选择手动,按照提示选择自己需要的即可。我选择了以下2个关键的。
- CSS Pre-processors
- scss(node scss)
- eslint(prettier)
- CSS Pre-processors
-
vue/cli有个小坑。如果删除了依赖,自己安装一遍,发现有警告⚠️:
warning " > sass-loader@8.0.2" has unmet peer dependency "webpack@^4.36.0 || ^5.0.0".
。应该是脚手架的坑,暂时不知怎么去改。
二. 使用vant
- 安装插件
yarn add vant
- 按需引入插件
yarn add babel-plugin-import --dev
(注:这个插件装到开发依赖) - 自动按需引入使用示例:
// template
<van-button type="default">默认按钮</van-button>
// script
import {
Button } from "vant";
components: {
[Button.name]: Button
}
三. 加入响应式布局
1. rem适配插件
- postcss-pxtorem 是一款 postcss 插件,用于将单位转化为 rem 。(!安装到开发依赖 --dev)
- lib-flexible 用于动态改变根节点的font-size,设置 rem 基准值。(!安装到生产依赖 --save)
- 【小坑】lib-flexible按照官网提供的在html引入js会报错,改为在main.js中引入依赖
import "amfe-flexible/index.js";
就ok了。
2. PostCSS配置
- vue.config.js中配置
css: { loaderOptions: { postcss: { plugins: [ require("autoprefixer")({ // 配置使用 autoprefixer overrideBrowserslist: ["last 15 versions"] }), require("postcss-pxtorem")({ rootValue: 37.5, // 换算的基数 // 忽略转换正则匹配项。插件会转化所有的样式的px。比如引入了三方UI,也会被转化。目前我使用 selectorBlackList字段,来过滤 //如果个别地方不想转化px。可以简单的使用大写的 PX 或 Px 。 selectorBlackList: ["ig"], propList: ["*"] }) ] } } }
- postcss.config.js中配置
module.exports = { plugins: { autoprefixer: { overrideBrowserslist: ['Android >= 4.0', 'iOS >= 8'], }, 'postcss-pxtorem': { rootValue: 37.5, // ⚠️这里是设计稿的1/10 propList: ['*'], mediaQuery: true }, }, };
在配置 postcss-loader 时,应避免 ignore node_modules 目录,否则将导致 Vant 样式无法被编译
四. 图标库:封装svg图标组件
- 原因:svg放大后不失真,可以像css一样设置颜色,非常方便。
- 使用步骤:
1. 建立如下目录结构:
icon
index.js
svg
test1.svg // (去阿里的iconfont随便下载一个来试验)
test2.svg
components
SvgIcon.vue
2. components/SvgIcon.vue
<template>
<svg :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: "SvgIcon",
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ""
}
},
computed: {
iconName() {
return `#icon-${
this.iconClass}`;
},
svgClass() {
if (this.className) {
return "svg-icon " + this.className;
} else {
return "svg-icon";
}
}
}
};
</script>
<style scoped>
.svg-icon {
width: 16px;
height: 16px;
vertical-align: -3px;
fill: currentColor;
overflow: hidden;
}
</style>
3. icon/index.js
import Vue from "vue";
import SvgIcon from "@/components/SvgIcon"; // svg组件
// register globally
Vue.component("svg-icon", SvgIcon);
const req = require.context("./svg", false, /\.svg$/);
const requireAll = requireContext => requireContext.keys().map(requireContext);
requireAll(req);
4. 配置vue.config.js
// 添加svg-sprite-loader,同时不要忽略了其他不作为图片的svg文件,