基于vuecli3构建的一个快速开发h5 APP的模板,集成了高德地图、mint-ui,以及antv-f2可视化框架

vue-cli3安装

  1. 查看vue cli版本 vue --version

  2. 要求nodejs版本8.9以上

  3. 如安装了旧版,使用npm uninstall vue-cli -g卸载旧版本

  4. 安装vue-cli3.0

    npm install -g @vue/cli

创建项目

  1. vue create hello-world

  2. 选择安装配置选项

  1. Babel
  2. TypeScript
  3. Progressive Web App (PWA) Support
  4. ❯◉ Router
  5. Vuex
  6. CSS Pre-processors
  7. Linter / Formatter
  8. Unit Testing
  9. E2E Testing
  10. ? Please pick a preset: Manually select features
  11. ? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter, Unit
  12. ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
  13. ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS
  14. ? Pick a linter / formatter config: Standard
  15. ? Pick additional lint features: Lint on save
  16. ? Pick a unit testing solution: Jest
  17. ? 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配置文件单独保存到配置文件中

  1. 项目运行及打包
  1. npm run serve
  2. 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文件,进行相关配置

  1. module.exports={
  2. }

使用vw方案手机屏幕适配

  1. 安装相关依赖
  1. 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
  1. 在postcss.config.js文件中添加如下配置
  1. module.exports = {
  2. plugins: {
  3. "postcss-import": {},
  4. "postcss-url": {},
  5. "postcss-aspect-ratio-mini": {},
  6. "postcss-write-svg": {
  7. utf8: false
  8. },
  9. "postcss-cssnext": {},
  10. "postcss-px-to-viewport": {
  11. viewportWidth: 750, // (Number) The width of the viewport.
  12. viewportHeight: 1334, // (Number) The height of the viewport.
  13. unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.
  14. viewportUnit: 'vw', // (String) Expected units.
  15. selectorBlackList: ['.ignore', '.hairlines'], // (Array) The selectors to ignore and leave as px.
  16. minPixelValue: 1, // (Number) Set the minimum pixel value to replace.
  17. mediaQuery: false // (Boolean) Allow px to be converted in media queries.
  18. },
  19. "postcss-viewport-units": {},
  20. "cssnano": {
  21. preset: "advanced",
  22. autoprefixer: false,
  23. "postcss-zindex": false
  24. },
  25. }
  26. }

vue-router

  1. 查询url参数
  1. this.wxcode = this.$route.query.code;
  1. 路由跳转
  1. this.$router.push({
  2. path: '/home'
  3. })
  1. 路由传参数 path方式
  1. this.$router.push({path: `/track/${this.curChildId}`})

路由设置

  1. {
  2. path:'/track/:cid',
  3. name: 'track',
  4. meta: {
  5. title: '历史轨迹'
  6. },
  7. component: () => import('@/pages/entry/track.vue')
  8. }

获取参数

  1. let cid = this.$route.params.cid;

vue定义过滤器的两种方式

1、在组件选项中定义本地的过滤器

  1. filters: {
  2. acceptFormat: function (value) {
  3. if(value==0){
  4. return '待授权'
  5. }else if(value==1){
  6. return '已授权'
  7. }
  8. return ''
  9. }
  10. }

使用

  1. <div>{{acceptStatus | acceptFormat}}</div>

2、全局定义过滤器

新建filters.js文件,添加filter过滤器

  1. /**
  2. * 授权状态
  3. * @param {*} value
  4. */
  5. export function acceptFormat(value) {
  6. if (value == 0) {
  7. return '待授权'
  8. } else if (value == 1) {
  9. return '已授权'
  10. }
  11. return ''
  12. }

在main,js文件中全局注册定义的过滤器

  1. // register filters
  2. Object.keys(filters).forEach(k => {
  3. console.log('k', k, filters[k])
  4. Vue.filter(k, filters[k])
  5. })

这样我们就可以在所有组件中使用了,不用单独在每个组件中重复定义

  1. <div>{{acceptStatus | acceptFormat}}</div>

配置路由按需加载

  1. const EntryIndex = () => import('@/pages/entry/Index.vue')
  2. const StatisticsIndex = () => import('@/pages/statistics/Index.vue')
  3. const MineIndex = () => import('@/pages/mine/Index.vue')
  4. const router = new Router({
  5. mode: 'history',
  6. base: process.env.BASE_URL,
  7. routes:[
  8. {
  9. name: 'home',
  10. path: 'home',
  11. component: EntryIndex
  12. }, {
  13. name: 'statistics',
  14. path: 'statistics',
  15. component: StatisticsIndex
  16. }, {
  17. name: 'mine',
  18. path: 'mine',
  19. component: MineIndex
  20. }
  21. ]
  22. })

vuecli3.x配置环境变量

在cli2.x中会有build和config两个文件夹 ,其中config下面就是用来配置不同环境下的环境变量,例如开发、测试、生产环境等

但在cli3.x中发现没有这两个文件夹,那该如何配置环境变量 ?

查看cli3.0文档 https://cli.vuejs.org/zh/guide/mode-and-env.html#模式

在项目根目录下新建以下文件

  1. .env
  2. .env.local // .local 在所有的环境中被载入,但会被 git 忽略
  3. .env.development
  4. .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中引入

  1. import MintUI from 'mint-ui'
  2. import 'mint-ui/lib/style.css'
  3. Vue.use(MintUI)

2、按需引入

按需引入需要借助 babel-plugin-component插件,这样可以只引入需要的组件,以达到减小项目体积的目的

  1. npm install babel-plugin-component -D

axios基本用法

  1. 1axios get请求
  2. Vue.axios.get('/api/get', {
  3. params: {
  4. name: '',
  5. age: 45
  6. }
  7. }).then((response) => {
  8. }).catch((error) => {
  9. });

2、axios post请求

  1. axios.post('/user', {
  2. firstName: 'Fred',
  3. lastName: 'Flintstone'
  4. })
  5. .then(function (response) {
  6. console.log(response);
  7. })
  8. .catch(function (error) {
  9. console.log(error);
  10. });

3、合并请求,同时执行多个请求

  1. axios.all([
  2. axios.get('https://api.github.com/xxx/1'),
  3. axios.get('https://api.github.com/xxx/2')
  4. ])
  5. .then(axios.spread(function (userResp, reposResp) {
  6. // 上面两个请求都完成后,才执行这个回调方法
  7. console.log('User', userResp.data);
  8. console.log('Repositories', reposResp.data);
  9. }));

axios接口请求封装

  1. src下创建api文件夹并新建index.js
  1. // api接口
  2. import Vue from 'vue'
  3. import axios from 'axios'
  4. import Qs from 'qs'
  5. /* eslint-disable */
  6. let api = {
  7. // 删除孩子信息
  8. delChild(params) {
  9. let postData = Qs.stringify(params)
  10. return Vue.axios.post('/api/v1/children_delete', postData)
  11. },
  12. // 获取孩子详情
  13. childDetail(params) {
  14. return Vue.axios.get('/api/v1/children_detail', params)
  15. },
  16. }
  17. export default function (Vue) {
  18. Vue.prototype.$api = api
  19. Vue.prototype.$fetch = axios
  20. }
  1. main.js中引入该文件
  1. import Api from './api'
  2. Vue.use(Api)
  1. 通过this.$api方式在vue中使用
  1. this.$api.sendVerifyCode({
  2. mobile:this.phone
  3. }).then((res)=>{
  4. })

问题总结

  1. 当vue router使用history模式,url带参数时页面刷新报错
  1. Uncaught SyntaxError: Unexpected token <

解决:

打开vue.config文件,配置publicPath为‘/’而不是'./'

  1. module.exports = {
  2. // 基本路径
  3. publicPath: '/',
  4. }
  1. vue-cli3出现Invalid Host header的解决方案

nginx配置了代理后出现 Invalid Host header

新版的webpack-dev-server增加了安全验证,默认检查hostname,如果hostname不是配置内的,将中断访问

解决:禁用主机检查,在根目录下创建文件vue.config.js,然后填入如下内容

  1. module.exports = {
  2. devServer: {
  3. disableHostCheck: true,
  4. }
  5. }
  1. vue移动端图片不显示问题解决

如果要对图片的样式进行设置可以指定class,但是宽高必须为100%

如果想指定图片的宽高只能用内联样式

  1. history模式部署问题 报404错误

服务器配置,当匹配不到路由时,跳转到index首页

tomcat配置方式

https://blog.csdn.net/elisunli/article/details/79823245

apache、nginx配置方式

https://router.vuejs.org/zh/guide/essentials/history-mode.html#后端配置例子

nodejs egg服务端路由配置

  1. router.get('*', controller.home.index);
  1. 使用Axios传参时 ,java后台接收不到值,后发现是Axios的传参请求是Payload方式

Form Data和Request Payload

解决:转换成Form Data的方式

  1. import Qs from 'qs'
  2. let postData = Qs.stringify(params)

或者

  1. let formData = new FormData()
  2. formData.append('score', score)
  3. formData.append('costtime', 0)
  1. vue-router使用beforeEach钩子获取vuex里的state值,初始页面报错

解决router.app.$store.state.user_info.userinfo

  1. let userinfo = router.app.$store.state.user_info.userinfo
  2. if (userinfo.token) {
  3. next()
  4. } else {
  5. // 跳转到登录页
  6. next({ name: 'login' })
  7. }

相关链接

最后

代码我已经放到github上面了,欢迎大家star或者fork

github地址

参考阅读

https://www.jianshu.com/p/f8430536059a

https://cli.vuejs.org/zh/guide/installation.html

基于vuecli3构建一个快速开发h5 APP的模板的更多相关文章

  1. 基于Jquery WeUI的微信开发H5页面控件的经验总结(2)

    在微信开发H5页面的时候,往往借助于WeUI或者Jquery WeUI等基础上进行界面效果的开发,由于本人喜欢在Asp.net的Web界面上使用JQuery,因此比较倾向于使用 jQuery WeUI ...

  2. Topshelf+Quartz3.0基于控制台应用程序快速开发可调度windows服务

    1.TopShelf TopShelf是一个开源的跨平台的宿主服务框架.可通过.Net Core/.Net Framwork控制台应用程序快速开发windows服务,更加便于服务调试. 本文基于.Ne ...

  3. 巧用第三方快速开发Android App 热门第三方SDK及框架

    巧用第三方快速开发Android App 热门第三方SDK及框架 历经大半年的时间,终于是把这门课程给录制出来了,也就在今天,正式在慕课网上上线了 项目地址:巧用第三方快速开发Android App ...

  4. 在线Online表单来了!JeecgBoot 2.1 版本发布——基于SpringBoot+AntDesign的快速开发平台

    项目介绍 Jeecg-Boot 是一款基于SpringBoot+代码生成器的快速开发平台! 采用前后端分离架构:SpringBoot,Ant-Design-Vue,Mybatis,Shiro,JWT. ...

  5. Reactjs-generator-cli 一款基于Ink构建用于快速搭建React应用的CLI scaffolding工具

    Reactjs-generator-cli 一款基于Ink构建用于快速搭建React应用的CLI scaffolding工具 A simple CLI for scaffolding React.js ...

  6. 基于SpringBoot+AntDesign的快速开发平台,JeecgBoot 2.0.2 版本发布

    Jeecg-Boot 是一款基于SpringBoot+代码生成器的快速开发平台! 采用前后端分离架构:SpringBoot,Ant-Design-Vue,Mybatis,Shiro,JWT. 强大的代 ...

  7. Sublime插件库新成员基于APICloud快速开发跨平台App

    互联网时代强调用户体验,那什么是HTML5跨平台App开发者的编程体验?“不剥夺.不替换开发者喜欢的开发工具,就是人性化的用户体验”,APICloud给出了这样的答案! 重磅发布“多开发工具支持策略” ...

  8. AgileRepository - 一个基于接口的Repository快速开发库

    AgileRepository 这是一个可以帮助你快速开发Repository的lib.有点像SpringData JPA根据方法名.注解来自动生成查询方法的功能. 对于一些简单的查询,只需要定义接口 ...

  9. 通过vue-cli3构建一个SSR应用程序

    1.前沿 1.1.什么是SSR SSR(服务端渲染)顾名思义就是将页面在服务端渲染完成后在客户端直接展示. 1.2.客户端渲染与服务端渲染的区别 传统的SPA模式 即客户端渲染的模式 Vue.js构建 ...

随机推荐

  1. 网络编程学习笔记-全零网络IP地址0.0.0.0详谈

    RFC: - Addresses in this block refer to source hosts on "this" network. Address may be use ...

  2. 【LeetCode】Maximum Product Subarray 求连续子数组使其乘积最大

    Add Date 2014-09-23 Maximum Product Subarray Find the contiguous subarray within an array (containin ...

  3. 生成0-42之间的7个不重复的int值

    public static void main(String[] args) { //set集合存储不重复无序的值 Set<Integer> set = new HashSet<In ...

  4. Scala学习——类,继承,接口(中)

    基本类的使用:(初) package com.dtspark.scala.basics /** * trait是一个接口 * 接口的第一次继承用extends,多继承时用with * 多继承时,如果这 ...

  5. ABP启动流程分析

    添加服务与注册中间件 public IServiceProvider ConfigureServices(IServiceCollection services) { // Configure Abp ...

  6. maven导入jar包失败

    找到原来的jar包位置,删除,然后重新导入,还是未成功.采取了网上的各种办法,还是不行.最简单的办法就是,重装下eclipse,以及maven配置.

  7. select2的远程加载非分页实例

    $("#c01-select").select2({ ajax: { url: "data.json", dataType: 'json', delay: 25 ...

  8. UVa 11552 Fewest Flops (DP)

    题意:给一个字符串,把它分为k块,每一块里面的字母可以任意的排序.最终字符串, 连续的一样的字母算作一个chunk,问总chunks最少是多少? 析:dp[i][j] 表示第 i 个块,第 j 位在末 ...

  9. ASP.NET学习笔记(五)ASP 对象

    1.ASP Response 对象用于从服务器向用户发送输出的结果. 2.ASP Request 对象用于从用户那里取得信息 Request.QueryString 命令用于搜集使用 method=& ...

  10. 给Fitnesse添加调用多参数fixture的调用方法

    修改文件:fitnesse.slim.fixtureInteraction.DefaultInteraction.java 修改如下三处内容: (注意只支持仅含有一个参数,且该参数是多参数的fixtu ...