#博学谷IT学习技术支持#
目录
一、项目初始化
(1) vue create toutiao-m
(2) 建立本地仓库推到线上
(3) 安装vant组件库
(4) 移动端 REM 适配
(5) 封装请求模块
一、项目初始化
(1) vue create toutiao-m
# 进入你的项目目录
cd toutiao-webapp
# 启动开发服务
npm run serve
(2) 建立本地仓库推到线上
# 创建本地仓库
git init
# 将文件添加到暂存区
git add .
# 提交历史记录
git commit "提交日志"
# 添加远端仓库地址
git remote add origin 你的远程仓库地址
# 推送提交
git push -u origin master
更新仓库并提交线上
git add .
git commit
git push
`router/index.js`
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
]
const router = new VueRouter({
routes
})
export default router
(3) 安装vant组件库
npm i vant
在 main.js 中加载注册 Vant 组件
import Vue from 'vue'
import Vant from 'vant'
import 'vant/lib/index.css'
Vue.use(Vant)
(4) 移动端 REM 适配
Vant 中的样式默认使用 px 作为单位,如果需要使用 rem 单位,推荐使用以下两个工具:
postcss-pxtorem 是一款 postcss 插件,用于将单位转化为 rem
lib-flexible 用于设置 rem 基准值
下面我们分别将这两个工具配置到项目中完成 REM 适配。
一、使用 lib-flexible 动态设置 REM 基准值(html 标签的字体大小)
1、安装
# yarn add amfe-flexible
npm i amfe-flexible
2、然后在 main.js 中加载执行该模块
import 'amfe-flexible'
最后测试:在浏览器中切换不同的手机设备尺寸,观察 html 标签 font-size 的变化。
二、使用 postcss-pxtorem 将 px 转为 rem
1、安装
# yarn add -D postcss-pxtorem
# -D 是 --save-dev 的简写
npm install postcss-pxtorem -D
2、然后在项目根目录中创建 .postcssrc.js 文件
module.exports = {
plugins: {
'autoprefixer': {
browsers: ['Android >= 4.0', 'iOS >= 8']
},
'postcss-pxtorem': {
rootValue: 37.5,
propList: ['*']
}
}
}
3、配置完毕,重新启动服务
最后测试:刷新浏览器页面,审查元素的样式查看是否已将 px 转换为 rem。
需要注意的是:
该插件不能转换行内样式中的 px,例如 <div style="width: 200px;"></div>
关于 .postcssrc.js 配置文件
module.exports = {
plugins: {
'autoprefixer': {
browsers: ['Android >= 4.0', 'iOS >= 8']
},
'postcss-pxtorem': {
rootValue: 37.5,
propList: ['*']
}
}
}
在vant中使用时,需要修改配置
/**
* PostCSS 配置文件
*/
module.exports = {
// 配置要使用的 PostCSS 插件
plugins: {
// 配置使用 autoprefixer 插件
// 作用:生成浏览器 CSS 样式规则前缀
// VueCLI 内部已经配置了 autoprefixer 插件
// 所以又配置了一次,所以产生冲突了
// 'autoprefixer': { // autoprefixer 插件的配置
// // 配置要兼容到的环境信息
// browsers: ['Android >= 4.0', 'iOS >= 8']
// },
// 配置使用 postcss-pxtorem 插件
// 作用:把 px 转为 rem
'postcss-pxtorem': {
rootValue ({ file }) {
return file.indexOf('vant') !== -1 ? 37.5 : 75
},
propList: ['*']
}
}
}
(5) 封装请求模块
和之前项目一样,这里我们还是使用 axios 作为我们项目中的请求库,为了方便使用,我们把它封装为一个请求模块,在需要的时候直接加载即可。
1、安装 axios
npm i axios
2、创建 src/utils/request.js
/**
* 封装 axios 请求模块
*/
import axios from "axios"
const request = axios.create({
baseURL: "http://ttapi.research.itcast.cn/" // 基础路径
})
export default request
3、如何使用
方式一(简单方便,但是不利于接口维护):我们可以把请求对象挂载到 Vue.prototype 原型对象中,然后在组件中通过 this.xxx 直接访问
方式二(推荐):我们把每一个请求都封装成每个独立的功能函数,在需要的时候加载调用,这种做法更便于接口的管理和维护
在我们的项目中建议使用方式二,更推荐(在随后的业务功能中我们就能学到)