uni-clientdb.vue 9.7 KB
Newer Older
芊里 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
<template>
  <view>
    <slot :options="options" :data="dataList" :pagination="paginationInternal" :loading="loading" :error="errorMessage"></slot>
  </view>
</template>

<script>
  const db = uniCloud.database();
  const dbCmd = db.command;

  const events = {
    load: 'load',
    error: 'error'
  }
  const pageMode = {
    add: 'add',
    replace: 'replace'
  }

  const attrs = [
    'collection',
    'action',
    'field',
    'pageCurrent',
    'pageSize',
    'getcount',
    'orderby',
    'where'
  ]

  /**
   * uni-clientdb
   * @description uni-clientdb是一个数据库查询组件,它是对uni-clientdb的js库的再封装。
   * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-clientdb-component
   * @property {String} collection 表名
   * @property {String} action 云端执行数据库查询的前或后,触发某个action函数操作,进行预处理或后处理
   * @property {String} field 查询字段,多个字段用 `,` 分割
   * @property {String} orderby 排序字段及正序倒叙设置
   * @property {String} where 查询条件
   * @property {String} pageData = [add|replace] `add` 多次查询的集合, `replace` 当前查询的集合
   * @value add 多次查询的集合
   * @value replace 当前查询的集合
   * @property {Number} pageCurrent 当前页
   * @property {Number} pageSize 每页数据数量
   * @property {Boolean} getone = [true|false] 指定查询结果是否返回数组第一条数据,默认 false。在false情况下返回的是数组,即便只有一条结果,也需要[0]的方式获取。在true下,直接返回结果数据,少一层数组
   * @value true 返回数组第一条数据
   * @value false 返回类型是数组,即便只有一条结果
   * @property {Boolean} getcount 是否查询总数量
   * @property {Boolean} manual 是否手动加载数据,默认为 false,页面onready时自动联网加载数据
   * @value true 开启后需要手动加载数据
   * @value false 页面onready时自动联网加载数据
   * @event {Function} load 成功回调。如联网返回结果后,想修改下数据再渲染界面,则在本方法里对data进行修改
   * @event {Function} error 失败回调
   */
  export default {
    name: 'UniClientdb',
    props: {
      options: {
        type: [Object, Array],
        default () {
          return {}
        }
      },
      collection: {
        type: String,
        default: ''
      },
      action: {
        type: String,
        default: ''
      },
      field: {
        type: String,
        default: ''
      },
      pageData: {
        type: String,
        default: 'add'
      },
      pageCurrent: {
        type: Number,
        default: 1
      },
      pageSize: {
        type: Number,
        default: 20
      },
      getcount: {
        type: [Boolean, String],
        default: false
      },
      orderby: {
        type: String,
        default: ''
      },
      where: {
        type: [String, Object],
        default: ''
      },
      getone: {
        type: [Boolean, String],
        default: false
      },
      manual: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        loading: false,
        dataList: [],
        paginationInternal: {
          current: this.pageCurrent,
          size: this.pageSize,
          count: 0
        },
        errorMessage: ''
      }
    },
    created() {
      this._isEnded = false

      this.$watch(() => {
        var al = []
        attrs.forEach(key => {
          al.push(this[key])
        })
        return al
      }, () => {
        this.clear()
        this.reset()
        this._execLoadData()
      })

      // #ifdef H5
      if (process.env.NODE_ENV === 'development') {
        this._debugDataList = []
        if (!window.unidev) {
          window.unidev = {
            clientDB: {
              data: []
            }
          }
        }
        unidev.clientDB.data.push(this._debugDataList)
      }
      // #endif

      // #ifdef MP-TOUTIAO
      let changeName
      let events = this.$scope.dataset.eventOpts
      for (var i = 0; i < events.length; i++) {
        let event = events[i]
        if (event[0].includes('^load')) {
          changeName = event[1][0][0]
        }
      }
      if (changeName) {
        let parent = this.$parent
        let maxDepth = 16
        this._changeDataFunction = null
        while (parent && maxDepth > 0) {
          let fun = parent[changeName]
          if (fun && typeof fun === 'function') {
            this._changeDataFunction = fun
            maxDepth = 0
            break
          }
          parent = parent.$parent
          maxDepth--;
        }
      }
      // #endif

      if (!this.manual) {
        this.loadData()
      }
    },
    // #ifdef H5
    beforeDestroy() {
      if (process.env.NODE_ENV === 'development' && window.unidev) {
        var cd = this._debugDataList
        var dl = unidev.clientDB.data
        for (var i = dl.length - 1; i >= 0; i--) {
          if (dl[i] === cd) {
            dl.splice(i, 1)
            break
          }
        }
      }
    },
    // #endif
    methods: {
      loadData(args1, args2) {
        let callback = null
        if (typeof args1 === 'object') {
          if (args1.clear) {
            this.clear()
            this.reset()
          }
          if (args1.current !== undefined) {
            this.paginationInternal.current = args1.current
          }
          if (typeof args2 === 'function') {
            callback = args2
          }
        } else if (typeof args1 === 'function') {
          callback = args1
        }

        this._execLoadData(callback)
      },
      loadMore() {
        if (this._isEnded) {
          return
        }
        this._execLoadData()
      },
      refresh() {
        this.clear()
        this._execLoadData()
      },
      clear() {
        this._isEnded = false
        this.dataList = []
      },
      reset() {
        this.paginationInternal.current = 1
      },
      remove(id, {
        action,
        callback,
        confirmTitle,
        confirmContent
      } = {}) {
        uni.showModal({
          title: confirmTitle || '提示',
          content: confirmContent || '是否删除该数据',
          showCancel: true,
          success: (res) => {
            if (!res.confirm) {
              return
            }
            this._execRemove(id, action, callback)
          }
        })
      },
      _execLoadData(callback) {
        if (this.loading) {
          return
        }
        this.loading = true
        this.errorMessage = ''

        this._getExec().then((res) => {
          this.loading = false
          const {
            data,
            count
          } = res.result
          this._isEnded = data.length < this.pageSize

          callback && callback(data, this._isEnded)
          this._dispatchEvent(events.load, data)

          if (this.getone) {
            this.dataList = data.length ? data[0] : undefined
          } else if (this.pageData === pageMode.add) {
            this.dataList.push(...data)
            if (this.dataList.length) {
              this.paginationInternal.current++
            }
          } else if (this.pageData === pageMode.replace) {
            this.dataList = data
            this.paginationInternal.count = count
          }

          // #ifdef H5
          if (process.env.NODE_ENV === 'development') {
            this._debugDataList.length = 0
            this._debugDataList.push(...JSON.parse(JSON.stringify(this.dataList)))
          }
          // #endif
        }).catch((err) => {
          this.loading = false
          this.errorMessage = err
          callback && callback()
          this.$emit(events.error, err)
        })
      },
      _getExec() {
        let exec = db
        if (this.action) {
          exec = exec.action(this.action)
        }

        exec = db.collection(this.collection)

        if (!(!this.where || !Object.keys(this.where).length)) {
          exec = exec.where(this.where)
        }
        if (this.field) {
          exec = exec.field(this.field)
        }
        if (this.orderby) {
          exec = exec.orderBy(this.orderby)
        }

        const {
          current,
          size
        } = this.paginationInternal
        exec = exec.skip(size * (current - 1)).limit(size).get({
          getCount: this.getcount
        })

        return exec
      },
      _execRemove(id, action, callback) {
        if (!this.collection || !id) {
          return
        }

        const ids = Array.isArray(id) ? id : [id]
        if (!ids.length) {
          return
        }

        uni.showLoading({
          mask: true
        })

        let exec = db
        if (action) {
          exec = exec.action(action)
        }

        exec.collection(this.collection).where({
          _id: dbCmd.in(ids)
        }).remove().then((res) => {
          callback && callback(res)
          if (this.pageData === pageMode.replace) {
            this.refresh()
          } else {
            this.removeData(ids)
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message,
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
      removeData(ids) {
        let il = ids.slice(0)
        let dl = this.dataList
        for (let i = dl.length - 1; i >= 0; i--) {
          let index = il.indexOf(dl[i]._id)
          if (index >= 0) {
            dl.splice(i, 1)
            il.splice(index, 1)
          }
        }
      },
      _dispatchEvent(type, data) {
        if (this._changeDataFunction) {
          this._changeDataFunction(data, this._isEnded)
        } else {
          this.$emit(type, data, this._isEnded)
        }
      }
    }
  }
</script>