在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:vue-vant-h5开源软件地址:https://gitee.com/mircle/vue-vant-h5开源软件介绍:vue-vant-h5基于 vue-cli4.0 + webpack 4 + vant ui + sass+ rem 适配方案+axios 封装,构建手机端模板脚手架 查看 demo 建议手机端查看
Node 版本要求
本示例 Node.js 12.14.1 启动项目git clone https://github.com/sunniejs/vue-vant-h5.gitcd vue-vant-h5npm installnpm run serve 目录
✅ 配置多环境变量
"scripts": { "serve": "vue-cli-service serve --open", "stage": "vue-cli-service build --mode test", "build": "vue-cli-service build",} 配置介绍 以 在项目根目录中新建
NODE_ENV='development'# must start with VUE_APP_VUE_APP_ENV = 'development'
NODE_ENV='production'# must start with VUE_APP_VUE_APP_ENV = 'test'
NODE_ENV='production'# must start with VUE_APP_VUE_APP_ENV = 'production' 这里我们并没有定义很多变量,只定义了基础的 VUE_APP_ENV 这里有个问题,既然这里有了根据不同环境设置变量的文件,为什么还要去 config 下新建三个对应的文件呢? config/index.js // 根据环境引入不同配置 process.env.NODE_ENVconst config = require('./env.' + process.env.VUE_APP_ENV)module.exports = config 配置对应环境的变量,拿本地环境文件 // 本地环境配置module.exports = { title: 'vue-vant-h5', baseUrl: 'http://localhost:9018', // 项目地址 baseApi: 'https://test.xxx.com/api', // 本地api请求地址 APPID: 'xxx', APPSECRET: 'xxx'} 根据环境不同,变量就会不同了 // 根据环境不同引入不同baseApi地址import { baseApi } from '@/config'console.log(baseApi) ✅ rem 适配方案不用担心,项目已经配置好了 Vant 中的样式默认使用
PostCSS 配置下面提供了一份基本的 // https://github.com/michael-ciniawsky/postcss-load-configmodule.exports = { plugins: { autoprefixer: { overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8'] }, 'postcss-pxtorem': { rootValue: 37.5, propList: ['*'] } }} 更多详细信息: vant 新手必看,老鸟跳过 很多小伙伴会问我,适配的问题,因为我们使用的是 Vant UI,所以必须根据 Vant UI 375 的设计规范走,一般我们的设计会将 UI 图上传到蓝湖,我们就可以需要的尺寸了。下面就大搞普及一下 rem。 我们知道 <html data-dpr="1" style="font-size: 37.5px;"></html> 切换不同的机型,根元素可能会有不同的 因为我们用了 Vant 的组件,需要按照 举个例子:设计给了你一张 750px * 1334px 图片,在 iPhone6 上铺满屏幕,其他机型适配。
也就是 iphone 6 下 375px 宽度写 CSS。其他的你就可以根据你设计图,去写对应的样式就可以了。 当然,想要撑满屏幕你可以使用 100%,这里只是举例说明。 <img class="image" src="https://imgs.solui.cn/weapp/logo.png" /><style> /* rootValue: 75 */ .image { width: 750px; height: 1334px; } /* rootValue: 37.5 */ .image { width: 375px; height: 667px; }</style> ✅ vm 适配方案本项目使用的是 rem 的 适配方案,其实无论你使用哪种方案,都不需要你去计算 12px 是多少 rem 或者 vw, 会有专门的工具去帮你做。如果你想用 vw,你可以按照下面的方式切换。 1.安装依赖npm install postcss-px-to-viewport -D 2.修改 .postcssrc.js将根目录下 .postcssrc.js 文件修改如下 // https://github.com/michael-ciniawsky/postcss-load-configmodule.exports = { plugins: { autoprefixer: { overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8'] }, 'postcss-px-to-viewport': { viewportWidth: 375, // 视窗的宽度,对应的是我们设计稿的宽度,一般是750 unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数(很多时候无法整除) viewportUnit: 'vw', // 指定需要转换成的视窗单位,建议使用vw selectorBlackList: ['.ignore', '.hairlines'], // 指定不转换为视窗单位的类,可以自定义,可以无限添加,建议定义一至两个通用的类名 minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位,你也可以设置为你想要的值 mediaQuery: false // 允许在媒体查询中转换`px` } }} 3.删除原来的 rem 相关代码src/main.js 删除如下代码 // 移动端适配import 'lib-flexible/flexible.js' package.json 删除如下代码 "lib-flexible": "^0.3.2","postcss-pxtorem": "^5.1.1", 运行起来,F12 元素 css 就是 vw 单位了 ✅ VantUI 组件按需加载项目采用Vant 自动按需引入组件 (推荐)下面安装插件介绍: babel-plugin-import 是一款 安装插件npm i babel-plugin-import -D 在 // 对于使用 babel7 的用户,可以在 babel.config.js 中配置const plugins = [ [ 'import', { libraryName: 'vant', libraryDirectory: 'es', style: true }, 'vant' ]]module.exports = { presets: [['@vue/cli-plugin-babel/preset', { useBuiltIns: 'usage', corejs: 3 }]], plugins} 使用组件项目在 // 按需全局引入 vant组件import Vue from 'vue'import { Button, List, Cell, Tabbar, TabbarItem } from 'vant'Vue.use(Button)Vue.use(Cell)Vue.use(List)Vue.use(Tabbar).use(TabbarItem) ✅ Sass 全局样式首先 你可能会遇到 每个页面自己对应的样式都写在自己的 .vue 文件之中 <style lang="scss"> /* global styles */</style><style lang="scss" scoped> /* local styles */</style> 目录结构vue-vant-h5 所有全局样式都在 ├── assets│ ├── css│ │ ├── index.scss # 全局通用样式│ │ ├── mixin.scss # 全局mixin│ │ └── variables.scss # 全局变量 自定义 vant-ui 样式现在我们来说说怎么重写 .about-container { /* 你的命名空间 */ .van-button { /* vant-ui 元素*/ margin-right: 0px; }} 父组件改变子组件样式 深度选择器当你子组件使用了 <style scoped>.a >>> .b { /* ... */ }</style> 全局变量
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)const defaultSettings = require('./src/config/index.js')module.exports = { css: { extract: IS_PROD, sourceMap: false, loaderOptions: { // 给 scss-loader 传递选项 scss: { // 注入 `sass` 的 `mixin` `variables` 到全局, $cdn可以配置图片cdn // 详情: https://cli.vuejs.org/guide/css.html#passing-options-to-pre-processor-loaders prependData: ` @import "assets/css/mixin.scss"; @import "assets/css/variables.scss"; $cdn: "${defaultSettings.$cdn}"; ` } } }} 设置 js 中可以访问 // 引入全局样式import '@/assets/css/index.scss'// 设置 js中可以访问 $cdn// 引入cdnimport { $cdn } from '@/config'Vue.prototype.$cdn = $cdn 在 css 和 js 使用 <script> console.log(this.$cdn)</script><style lang="scss" scoped> .logo { width: 120px; height: 120px; background: url($cdn + '/weapp/logo.png') center / contain no-repeat; }</style> ✅ Vuex 状态管理目录结构 ├── store│ ├── modules│ │ └── app.js│ ├── index.js│ ├── getters.js
import Vue from 'vue'import App from './App.vue'import store from './store'new Vue({ el: '#app', router, store, render: h => h(App)}) 使用 <script> import { mapGetters } from 'vuex' export default { computed: { ...mapGetters(['userName']) }, methods: { // Action 通过 store.dispatch 方法触发 doDispatch() { this.$store.dispatch('setUserName', '真乖,赶紧关注公众号,组织都在等你~') } } }</script> ✅ Vue-router本案例采用 注意:如果你使用了 import Vue from 'vue'import Router from 'vue-router'Vue.use(Router)export const router = [ { path: '/', name: 'index', component: () => import('@/views/home/index'), // 路由懒加载 meta: { title: '首页', // 页面标题 keepAlive: false // keep-alive 标识 } }]const createRouter = () => new Router({ // mode: 'history', // 如果你是 history模式 需要配置 vue.config.js publicPath // base: '/app/', scrollBehavior: () => ({ y: 0 }), routes: router })export default createRouter() 更多:Vue Router ✅ Axios 封装及接口管理
import axios from 'axios'import store from '@/store'import { Toast } from 'vant'// 根据环境不同引入不同api地址import { baseApi } from '@/config'// create an axios instanceconst service = axios.create({ baseURL: baseApi, // url = base api url + request url withCredentials: true, // send cookies when cross-domain requests timeout: 5000 // request timeout})// request 拦截器 request interceptorservice.interceptors.request.use( config => { // 不传递默认开启loading if (!config.hideloading) { // loading Toast.loading({ forbidClick: true }) } if (store.getters.token) { config.headers['X-Token'] = '' } return config }, error => { // do something with request error console.log(error) // for debug return Promise.reject(error) })// respone拦截器service.interceptors.response.use( response => { Toast.clear() const res = response.data if (res.status && res.status !== 200) { // 登录超时,重新登录 if (res.status === 401) { store.dispatch('FedLogOut').then(() => { location.reload() }) } return Promise.reject(res || 'error') } else { return Promise.resolve(res) } }, error => { Toast.clear() console.log('err' + error) // for debug return Promise.reject(error) })export default service 接口管理在
import qs from 'qs'// axiosimport request from '@/utils/request'//user api// 用户信息export function getUserInfo(params) { return request({ url: '/user/userinfo', method: 'post', data: qs.stringify(params), hideloading: true // 隐藏 loading 组件 })} 如何调用// 请求接口import { getUserInfo } from '@/api/user.js'const params = { user: 'sunnie' }getUserInfo(params) .then(() => {}) .catch(() => {}) ✅ Webpack 4 vue.config.js 基础配置如果你的 publicPath: './', 如果你的 publicPath: '/app/', const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)module.exports = { publicPath: './', // 署应用包时的基本 URL。 vue-router hash 模式使用 // publicPath: '/app/', // 署应用包时的基本 URL。 vue-router history模式使用 outputDir: 'dist', // 生产环境构建文件的目录 assetsDir: 'static', // outputDir的静态资源(js、css、img、fonts)目录 lintOnSave: !IS_PROD, productionSourceMap: false, // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。 devServer: { port: |
请发表评论