vue+vant+rem+axios 移动端项目初始化
一、创建项目
- 先建立一个文件夹并使用 cmd 打开
- 进入 cmd 使用 vue create . 创建项目(隔空格)
接下来出现
Vue CLI v4.5.11
? Generate project in current directory? (Y/n)//在当前目录中生成项目?
回答 y
接下来出现
nanfeng2 ([Vue 2] less, babel, router, vuex, eslint)
clerk ([Vue 2] less, babel, pwa, router, vuex, eslint)
clerk2 ([Vue 2] less, babel, router, vuex, eslint)
Default ([Vue 2] babel, eslint)
Default (Vue 3 Preview) ([Vue 3] babel, eslint)
Manually select features
除了 Default 和 Manually nanfeng2 和 clerk 都是之前构建项目保留的记录,如果本次选择了就会直接开始构建
所以我们选择最后一个 Manually 手动构建项目 (在 cmd 中使用上下箭头移动选项)
- 选择 Manually 按下回车
? 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)
>(*) Choose Vue version
(*) Babel
( ) TypeScript
( ) Progressive Web App (PWA) Support
( ) Router
( ) Vuex
( ) CSS Pre-processors
(*) Linter / Formatter
( ) Unit Testing
( ) E2E Testing
出现以上代码,通过上下箭头(移动)和空格键(选择)
这里我们这样选择
? Please pick a preset: Manually select features
? Check the features needed for your project:
(*) Choose Vue version
(*) Babel
( ) TypeScript
( ) Progressive Web App (PWA) Support
(*) Router
(*) Vuex
>(*) CSS Pre-processors
(*) Linter / Formatter
( ) Unit Testing
( ) E2E Testing
然后按下回车
? Choose a version of Vue.js that you want to start the project with (Use arrow keys)
> 2.x
3.x (Preview)
这里我们选择 2.x 按下回车继续
Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) //询问我们是否使用history模式
这里我们打 n,不选择历史模式
? 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): (Use arrow keys)
> Sass/SCSS (with dart-sass)
Sass/SCSS (with node-sass)
Less
Stylus
接下来选择 css 扩展 这里选择 less
接着出现
> ESLint with error prevention only
ESLint + Airbnb config
ESLint + Standard config
ESLint + Prettier
我们选择最后一个
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>(*) 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
这里我们选择单独配置文件,而不是全部在 package.json 文件里
接下来出现
? Save this as a preset for future projects? (y/N) y//保存
? Save this as a preset for future projects? Yes
? Save preset as: //起个名字
接下来等待一段事件,项目构建完成。
二、在根目录建立 vue.config.js 文件
三、初始化样式
npm i reset-css
//安装完成 然后 main.js 中引入
import "reset-css";
四、rem 配置
npm i lib-flexible postcss-px2rem
//安装完成 在main.js 引入
import 'lib-flexible'
然后在 vue.config.js中配置以下内容
module.exports = {
// lintOnSave:false,//关闭eslint校验
//filennameHashing:true,//默认true 生成的打包文件是否启用hash,适用hash可以更好的控制缓存
publicPath: process.env.NODE_ENV === "production" ? "./" : "/",//解决打包后打开项目一片空白 如果是history模式需要注释路由里的mode:'history'
productionSourceMap: false,//关闭打包后出现的map文件
devServer: {
open: true,//是否自动打开浏览器
port: 5000,//端口号
proxy: {//配置代理跨域
"/api": {
target: "http://baidu.com",//配置需要跨域的根地址
changeOrigin: true,//changeOrigin是false:请求头中host仍然是浏览器发送过来的host;如果设置成true:发送请求头中host会设置成target。
secure: false,// 如果是https接口,需要配置这个参数
pathRewrite: { // 发送请求时,请求路径重写:将 /api/xxx --> /xxx (去掉/api)
"^/api": "",
},
},
},
},
// rem 的配置
css: {
loaderOptions: {
css: {},
postcss: {
plugins: [
require('postcss-px2rem')({
// 适配 375 屏幕, 设计图750中量出来的尺寸要 / 2
// 配置成 37.5 是为了兼容 没有适配 rem 布局的第三方 ui 库
remUnit: 37.5
})
]
}
}
}
};
五、axios 配置
npm i axios
//安装完成 src目录下建request文件夹 文件夹下建立request.js
//request.js内容如下
import axios from "axios"
const instance = axios.create({
baseURL:"http://baidu.com",//根请求
timeout:5000//超时时间
});
// 拦截器
instance.interceptors.request.use(config=>{
//什么时候执行这个函数? 发请求之前执行这个函数
// 可以判断用户有没有登录, 如果没有登录,
// console.log("config:",config); // 本次请求的一些信息
let token = localStorage.getItem("token");
if(token){
// 携带登录凭证发起请求
config.headers["X-Nideshop-Token"] = token
}
config.headers = {//设置请求头
"content-type": "application/x-www-form-urlencoded", //默认application/json 不需要处理
};
config.transformRequest = [//对应 application/x-www-form-urlencoded 请求头中请求参数处理
function(data) {
let ret = "";
for (let it in data) {
ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
}
return ret;
},
];
return config;
},
return config
},err=>{
return Promise.reject(err)
})
instance.interceptors.response.use(res=>{
//什么时候执行这个函数? 在接收到响应之前,在执行then方法之前
// console.log("res:", res); // 本次服务器响应的一些信息
return res.data // 返回的这个res 被then方法的res形参接收了
},err=>{
return Promise.reject(err)
})
export default instance
在 request 文件夹下建 api.js 文件 统一管理接口 实现按需导出
import request from "./request"
export const indexList=params=>request.post('/getAreaListByPy',params)
export const businessType=params=>request.get('/businessType',{params})
//在页面中使用 首先导入
import { indexList, businessType } from "@/request/api";
//比如在 created 生命周期中调用
created() {
indexList({ cityPy: "bei" })
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
businessType({ cityPy: "bei" })
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
},
六、vant ui 配置
npm i vant
//安装完成 后 我们使用的是按需引入
在 src 目录下建文件夹 vantui 里面 建立index.js文件
index.js 文件内容如下
import Vue from "vue";
import {
Tabbar,
TabbarItem,
Toast,
Button,
Search,
Swipe,
SwipeItem,
Icon,
Tag,
List,
Cell,
DropdownMenu,
DropdownItem,
Empty,
Checkbox,
CheckboxGroup,
Col,
Sku,
Row,
Grid,
GridItem,
Form,
Field,
GoodsAction,
GoodsActionIcon,
GoodsActionButton,
Card,
SubmitBar,
Stepper,
SwipeCell,
} from "vant";
Vue.use(SwipeCell);
Vue.use(Stepper);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Sku);
Vue.use(GoodsAction);
Vue.use(GoodsActionButton);
Vue.use(GoodsActionIcon);
Vue.use(Card);
Vue.use(Form);
Vue.use(Field);
Vue.use(SubmitBar);
Vue.use(Grid);
Vue.use(GridItem);
Vue.use(Col);
Vue.use(Row);
Vue.use(Tabbar);
Vue.use(TabbarItem);
Vue.use(Toast);
Vue.use(Empty);
Vue.use(DropdownMenu);
Vue.use(DropdownItem);
Vue.use(List);
Vue.use(Tag);
Vue.use(Icon);
Vue.use(Swipe);
Vue.use(SwipeItem);
Vue.use(Search);
Vue.use(Button);
Vue.use(Cell);
接着 在 main.js 中引入
import "@/vantui";
如果这时候去使用 vantui 中的组件会发现没有样式
//首先命令行安装 babel-plugin-import
npm i babel-plugin-import
然后我们需要配置按需引入对应的样式配置
打开 babel.config.js 配置
plugins: [
[
"import",
{
libraryName: "vant",
libraryDirectory: "es",
style: true,
},
"vant",
],
];
至此我们的配置告一段落
git地址 https://gitee.com/southWindNumber/vue_mobile_demo.git