1. 程式人生 > >基於vuecli3構建一個快速開發h5 APP的模板

基於vuecli3構建一個快速開發h5 APP的模板

基於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. 選擇安裝配置選項

◉ 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配置檔案單獨儲存到配置檔案中

  1. 專案執行及打包
npm run serve

npm run build

新增外掛

在專案中新增外掛使用vue add,如:vue add axios

vue.config.js配置檔案

https://cli.vuejs.org/zh/config/#%E5%85%A8%E5%B1%80-cli-%E9%85%8D%E7%BD%AE

3.0和2.0不同的是,webpack相關的配置檔案都被隱藏了,如果需要配置,則通過vue.config.js來配置

根目錄下新建vue.config.js檔案,進行相關配置

module.exports={
  
}

使用vw方案手機螢幕適配

  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檔案中新增如下配置
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

  1. 查詢url引數
    this.wxcode = this.$route.query.code;
  1. 路由跳轉
    this.$router.push({
              path: '/home'
          })
  1. 路由傳引數 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#%E6%A8%A1%E5%BC%8F

在專案根目錄下新建以下檔案

.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介面請求封裝

  1. 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
}
  1. main.js中引入該檔案
import Api from './api'
Vue.use(Api)
  1. 通過this.$api方式在vue中使用
this.$api.sendVerifyCode({
        mobile:this.phone
      }).then((res)=>{
      })

問題總結

  1. 當vue router使用history模式,url帶引數時頁面重新整理報錯
Uncaught SyntaxError: Unexpected token <

解決:
開啟vue.config檔案,配置publicPath為‘/’而不是'./'

module.exports = {
  // 基本路徑
  publicPath: '/',
}
  1. vue-cli3出現Invalid Host header的解決方案

nginx配置了代理後出現 Invalid Host header

新版的webpack-dev-server增加了安全驗證,預設檢查hostname,如果hostname不是配置內的,將中斷訪問
解決:禁用主機檢查,在根目錄下建立檔案vue.config.js,然後填入如下內容

module.exports = {
    devServer: {
        disableHostCheck: true,
    }
}
  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#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90

nodejs egg服務端路由配置

router.get('*', controller.home.index);
  1. 使用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)
      
  1. 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元件
    高德原生

  • mint-ui框架
    mint-ui

  • vue-cli3.x文件
    vue-cli3.x

  • antv-f2移動端視覺化ui框架
    antv-f2

最後

程式碼我已經放到github上面了,歡迎大家star或者fork
github地址

參考閱讀

https://www.jianshu.com/p/f8430536059a
https://cli.vuejs.org/zh/guide/installation.h