基于 vuecli3 构建的一个快速开发 h5 App 的模板, 集成了高德地图, mint-ui, 以及 antv-f2 可视化框架
vue-cli3 安装
查看 vue cli 版本 vue --version
要求 Node.JS 版本 8.9 以上
如安装了旧版, 使用 NPM uninstall vue-cli -g 卸载旧版本
安装 vue-cli3.0
NPM install -g @vue/cli
创建项目
vue create hello-world
选择安装配置选项
- 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: Babel, Router, Vuex, CSS Pre-processors, Linter, Unit
- ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
- ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS
- ? Pick a linter / formatter config: Standard
- ? Pick additional lint features: Lint on save
- ? Pick a unit testing solution: Jest
- ? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? In dedicated config files
配置选项说明
CSS 预编译使用 Sass/SCSS
代码检查使用 Standard 保存时检查 Lint on save
单元测试工具 Jest
Babel, PostCSS, ESLint 配置文件单独保存到配置文件中
项目运行及打包
- NPM run serve
- NPM run build
添加插件
在项目中添加插件使用 vue add, 如: vue add axios
vue.config.JS 配置文件
https://cli.vuejs.org/zh/config/#全局-cli-配置
3.0 和 2.0 不同的是, webpack 相关的配置文件都被隐藏了, 如果需要配置, 则通过 vue.config.JS 来配置
根目录下新建 vue.config.JS 文件, 进行相关配置
- module.exports={
- }
使用 vw 方案手机屏幕适配
安装相关依赖
NPM i postcss-aspect-ratio-mini postcss-px-to-viewport postcss-write-svg postcss-cssnext postcss-viewport-units cssnano cssnano-preset-advanced postcss-import postcss-url --S
在 postcss.config.JS 文件中添加如下配置
- module.exports = {
- plugins: {
- "postcss-import": {},
- "postcss-url": {},
- "postcss-aspect-ratio-mini": {},
- "postcss-write-svg": {
- utf8: false
- },
- "postcss-cssnext": {},
- "postcss-px-to-viewport": {
- viewportWidth: 750, // (Number) The width of the viewport.
- viewportHeight: 1334, // (Number) The height of the viewport.
- unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.
- viewportUnit: 'vw', // (String) Expected units.
- selectorBlackList: ['.ignore', '.hairlines'], // (Array) The selectors to ignore and leave as px.
- minPixelValue: 1, // (Number) Set the minimum pixel value to replace.
- mediaQuery: false // (Boolean) Allow px to be converted in media queries.
- },
- "postcss-viewport-units": {},
- "cssnano": {
- preset: "advanced",
- autoprefixer: false,
- "postcss-zindex": false
- },
- }
- }
- vue-router
查询 url 参数
this.wxcode = this.$route.query.code;
路由跳转
- this.$router.push({
- path: '/home'
- })
路由传参数 path 方式
this.$router.push({path: `/track/${this.curChildId}`})
路由设置
- {
- path:'/track/:cid',
- name: 'track',
- meta: {
- title: '历史轨迹'
- },
- component: () => import('@/pages/entry/track.vue')
- }
获取参数
let cid = this.$route.params.cid;
vue 定义过滤器的两种方式
1, 在组件选项中定义本地的过滤器
- filters: {
- acceptFormat: function (value) {
- if(value==0){
- return '待授权'
- }else if(value==1){
- return '已授权'
- }
- return ''
- }
- }
使用
<div>{{acceptStatus | acceptFormat}}</div>
2, 全局定义过滤器
新建 filters.JS 文件, 添加 filter 过滤器
- /**
- * 授权状态
- * @param {*} value
- */
- export function acceptFormat(value) {
- if (value == 0) {
- return '待授权'
- } else if (value == 1) {
- return '已授权'
- }
- return ''
- }
在 main,JS 文件中全局注册定义的过滤器
- // register filters
- Object.keys(filters).forEach(k => {
- console.log('k', k, filters[k])
- Vue.filter(k, filters[k])
- })
这样我们就可以在所有组件中使用了, 不用单独在每个组件中重复定义
<div>{{acceptStatus | acceptFormat}}</div>
配置路由按需加载
- const EntryIndex = () => import('@/pages/entry/Index.vue')
- const StatisticsIndex = () => import('@/pages/statistics/Index.vue')
- const MineIndex = () => import('@/pages/mine/Index.vue')
- const router = new Router({
- mode: 'history',
- base: process.env.BASE_URL,
- routes:[
- {
- name: 'home',
- path: 'home',
- component: EntryIndex
- }, {
- name: 'statistics',
- path: 'statistics',
- component: StatisticsIndex
- }, {
- name: 'mine',
- path: 'mine',
- component: MineIndex
- }
- ]
- })
vuecli3.x 配置环境变量
在 cli2.x 中会有 build 和 config 两个文件夹 , 其中 config 下面就是用来配置不同环境下的环境变量, 例如开发, 测试, 生产环境等
但在 cli3.x 中发现没有这两个文件夹, 那该如何配置环境变量 ?
查看 cli3.0 文档 https://cli.vuejs.org/zh/guide/mode-and-env.html#模式
在项目根目录下新建以下文件
- .env
- .env.local // .local 在所有的环境中被载入, 但会被 Git 忽略
- .env.development
- .env.production
然后在文件中设置 "键 = 值" 的形式
例如 VUE_APP_SECRET=secret
如果我们在应用中使用环境变量 , 那么在. env 中必须设置以 VUE_APP_开头的健 = 值, 否则无法访问到, 而在 webpack 中可以正常使用
process.env.VUE_APP_SECRET
vue cli 一般会有三个模式
development 模式用于 vue-cli-service serve
production 模式用于 vue-cli-service build 和 vue-cli-service test:e2e
test 模式用于 vue-cli-service test:unit
集成 mint-ui 移动端 ui 框架
饿了么出品 http://mint-ui.github.io/docs/#/zh-cn2/quickstart
NPM i mint-ui -S
1, 全部引入
然后在 main.JS 中引入
- import MintUI from 'mint-ui'
- import 'mint-ui/lib/style.css'
- Vue.use(MintUI)
2, 按需引入
按需引入需要借助 babel-plugin-component 插件, 这样可以只引入需要的组件, 以达到减小项目体积的目的
NPM install babel-plugin-component -D
axios 基本用法
1,axios get 请求
- Vue.axios.get('/api/get', {
- params: {
- name: '',
- age: 45
- }
- }).then((response) => {
- }).catch((error) => {
- });
2,axios post 请求
- axios.post('/user', {
- firstName: 'Fred',
- lastName: 'Flintstone'
- })
- .then(function (response) {
- console.log(response);
- })
- .catch(function (error) {
- console.log(error);
- });
3, 合并请求, 同时执行多个请求
- axios.all([
- axios.get('https://api.github.com/xxx/1'),
- axios.get('https://api.github.com/xxx/2')
- ])
- .then(axios.spread(function (userResp, reposResp) {
- // 上面两个请求都完成后, 才执行这个回调方法
- console.log('User', userResp.data);
- console.log('Repositories', reposResp.data);
- }));
axios 接口请求封装
src 下创建 API 文件夹并新建 index.JS
- // API 接口
- import Vue from 'vue'
- import axios from 'axios'
- import Qs from 'qs'
- /* eslint-disable */
- let API = {
- // 删除孩子信息
- delChild(params) {
- let postData = Qs.stringify(params)
- return Vue.axios.post('/api/v1/children_delete', postData)
- },
- // 获取孩子详情
- childDetail(params) {
- return Vue.axios.get('/api/v1/children_detail', params)
- },
- }
- export default function (Vue) {
- Vue.prototype.$API = API
- Vue.prototype.$fetch = axios
- }
main.JS 中引入该文件
- import API from './api'
- Vue.use(API)
通过 this.$API 方式在 vue 中使用
- this.$API.sendVerifyCode({
- mobile:this.phone
- }).then((res)=>{
- })
问题总结
当 vue router 使用 history 模式, url 带参数时页面刷新报错
Uncaught SyntaxError: Unexpected token <
解决:
打开 vue.config 文件, 配置 publicPath 为'/'而不是'./'
- module.exports = {
- // 基本路径
- publicPath: '/',
- }
vue-cli3 出现 Invalid Host header 的解决方案
nginx 配置了代理后出现 Invalid Host header
新版的 webpack-dev-server 增加了安全验证, 默认检查 hostname, 如果 hostname 不是配置内的, 将中断访问
解决: 禁用主机检查, 在根目录下创建文件 vue.config.JS, 然后填入如下内容
- module.exports = {
- devServer: {
- disableHostCheck: true,
- }
- }
vue 移动端图片不显示问题解决
如果要对图片的样式进行设置可以指定 class, 但是宽高必须为 100%
如果想指定图片的宽高只能用内联样式
history 模式部署问题 报 404 错误
服务器配置, 当匹配不到路由时, 跳转到 index 首页
tomcat 配置方式
https://blog.csdn.net/elisunli/article/details/79823245
apache,nginx 配置方式
https://router.vuejs.org/zh/guide/essentials/history-mode.html#后端配置例子
Node.JS egg 服务端路由配置
router.get('*', controller.home.index);
使用 Axios 传参时 ,java 后台接收不到值, 后发现是 Axios 的传参请求是 Payload 方式
Form Data 和 Request Payload
解决: 转换成 Form Data 的方式
- import Qs from 'qs'
- let postData = Qs.stringify(params)
或者
- let formData = new FormData()
- formData.append('score', score)
- formData.append('costtime', 0)
vue-router 使用 beforeEach 钩子获取 vuex 里的 state 值, 初始页面报错
解决 router.App.$store.state.user_info.userinfo
- let userinfo = router.App.$store.state.user_info.userinfo
- if (userinfo.token) {
- next()
- } else {
- // 跳转到登录页
- next({ name: 'login' })
- }
相关链接
高德地图
amap 高德地图 vue 组件 https://elemefe.github.io/vue-amap/#/
高德原生 https://lbs.amap.com/api/javascript-api/summary
mint-ui 框架
http://mint-ui.github.io/#!/zh-cn
vue-cli3.x 文档
vue-cli3.x https://cli.vuejs.org/zh/
antv-f2 移动端可视化 ui 框架
antv-f2 https://antv.alipay.com/zh-cn/f2/3.x/
最后
代码我已经放到 GitHub 上面了, 欢迎大家 star 或者 fork
GitHub 地址 https://github.com/fozero/VUECLI3-H5
参考阅读
- https://www.jianshu.com/p/f8430536059a
- https://cli.vuejs.org/zh/guide/installation.html
来源: https://www.cnblogs.com/fozero/p/10939290.html