定制快应用项目

740 阅读1分钟

快应用项目配置


初始化项目

1. npm install -g hap-toolkit
2. hap init quickDemo
3. npm install

启动项目

1. npm run watch 
2. npm run server
3. 快应用开发者工具预览

目录分析

主开发目录为src,manifest.json项目配置文件,app.ux 项目入口文件

配置网络请求

  1. 网络库flyio github.com/wendux/fly
import fetch from "@system.fetch"
import Fly from "flyio/dist/npm/hap"
const fly = new Fly(fetch)
  1. 自定义网络请求 httpPlugin
export default makeInstance (app) => {
    // app 将快应用实例传入 可以获取挂载在app上的属性和方法
    return ({}) => {
        fly.request({}).then((data) => {
            // 数据返回同意处理
        })
    }
}
  1. 挂载到快应用实例上
// app.ux
  async onCreate () {
    // 获取应用信息
    this.appInfo = app.getInfo()
    // 挂在网络请求
    this.$http = httpPlugin(this)
  }
  1. 使用
    this.$app.$http({url: ''}).then((data) => {
      console.log(data)
    })

优化

  1. 支持async await
    1.1 创建文件 regenerator.js
    const injectRef = Object.getPrototypeOf(global) || global
    
    // 注入regeneratorRuntime
    injectRef.regeneratorRuntime = require('@babel/runtime/regenerator')
    export default injectRef.regeneratorRuntime
    
    1.2 app.ux 引用
    import regenerator from './regenerator.js'
    
  2. 重写JSON.parse,通过快应用接口获取信息时,如果获取失败时JSON.parse会报错
function parseProxy () {
    const rawParse = JSON.parse
    JSON.parse = function (str, defaults) {
      try {
        return rawParse(str)
      }
      catch (err) {
        console.error(`JSON解析失败:${str}, ${err.stack}`)
        return defaults
      }
    }
  }

公共方法 util.js

/**
 * 获取地理位置信息
 */
function getLocation () {
  const geolocation  = require('@system.geolocation')
  return new Promise((reslove,reject) => {
    geolocation.getLocation({
      success: (data) => {
        reslove(data)
      },
      fail: (data, code) => {
        reslove({latitude: '', longitude: ''})
      }
    })
  })
}
export default {
  getLocation
}

挂载到app上

<script>
/**
* 应用级别的配置,供所有页面公用
*/
import util from './util'
export default {
  getLocation: util.getLocation,
  async onCreate () {
    // 获取应用信息
    this.appInfo = app.getInfo()
    // 挂在路由
    this.router = router
    // 获取设备信息
    this.deviceInfo = await util.getDeviceInfo()
    // 获取地理位置
    try {
      this.locationInfo = await util.getLocation()
    } catch (code) {
        console.log(code)      
    }
  }
}
</script>