unicloud-db.vue 10.0 KB
Newer Older
d-u-a's avatar
d-u-a 已提交
1 2
<template>
  <view>
d-u-a's avatar
d-u-a 已提交
3
    <slot :options="options" :data="dataList" :pagination="paginationInternal" :loading="loading" :error="errorMessage" />
d-u-a's avatar
d-u-a 已提交
4 5 6 7
  </view>
</template>

<script>
d-u-a's avatar
d-u-a 已提交
8 9 10 11 12 13 14 15
  const events = {
    load: 'load',
    error: 'error'
  }
  const pageMode = {
    add: 'add',
    replace: 'replace'
  }
d-u-a's avatar
d-u-a 已提交
16

d-u-a's avatar
d-u-a 已提交
17 18 19 20 21 22 23 24 25 26
  const attrs = [
    'pageCurrent',
    'pageSize',
    'collection',
    'action',
    'field',
    'getcount',
    'orderby',
    'where'
  ]
d-u-a's avatar
d-u-a 已提交
27

d-u-a's avatar
d-u-a 已提交
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
  export default {
    name: 'UniClouddb',
    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
d-u-a's avatar
d-u-a 已提交
80 81
      }
    },
d-u-a's avatar
d-u-a 已提交
82 83 84 85 86 87 88 89 90 91 92
    data() {
      return {
        loading: false,
        dataList: this.getone ? {} : [],
        paginationInternal: {
          current: this.pageCurrent,
          size: this.pageSize,
          count: 0
        },
        errorMessage: ''
      }
d-u-a's avatar
d-u-a 已提交
93
    },
d-u-a's avatar
d-u-a 已提交
94 95
    created() {
      this._isEnded = false
d-u-a's avatar
d-u-a 已提交
96

d-u-a's avatar
d-u-a 已提交
97 98 99 100 101 102 103 104
      this.$watch(() => {
        var al = []
        attrs.forEach(key => {
          al.push(this[key])
        })
        return al
      }, (newValue, oldValue) => {
        this.paginationInternal.pageSize = this.pageSize
d-u-a's avatar
d-u-a 已提交
105

d-u-a's avatar
d-u-a 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118
        let needReset = false
        for (let i = 2; i < newValue.length; i++) {
          if (newValue[i] !== oldValue[i]) {
            needReset = true
            break
          }
        }
        if (needReset) {
          this.clear()
          this.reset()
        }
        if (newValue[0] !== oldValue[0]) {
          this.paginationInternal.current = this.pageCurrent
d-u-a's avatar
d-u-a 已提交
119 120
        }

d-u-a's avatar
d-u-a 已提交
121 122
        this._execLoadData()
      })
d-u-a's avatar
d-u-a 已提交
123

d-u-a's avatar
d-u-a 已提交
124 125 126 127 128 129 130 131
      // #ifdef H5
      if (process.env.NODE_ENV === 'development') {
        this._debugDataList = []
        if (!window.unidev) {
          window.unidev = {
            clientDB: {
              data: []
            }
d-u-a's avatar
d-u-a 已提交
132 133
          }
        }
d-u-a's avatar
d-u-a 已提交
134
        window.unidev.clientDB.data.push(this._debugDataList)
d-u-a's avatar
d-u-a 已提交
135
      }
d-u-a's avatar
d-u-a 已提交
136
      // #endif
d-u-a's avatar
d-u-a 已提交
137

d-u-a's avatar
d-u-a 已提交
138 139 140 141 142 143 144 145
      // #ifdef MP-TOUTIAO
      let changeName
      const events = this.$scope.dataset.eventOpts
      for (var i = 0; i < events.length; i++) {
        const event = events[i]
        if (event[0].includes('^load')) {
          changeName = event[1][0][0]
        }
d-u-a's avatar
d-u-a 已提交
146
      }
d-u-a's avatar
d-u-a 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159
      if (changeName) {
        let parent = this.$parent
        let maxDepth = 16
        this._changeDataFunction = null
        while (parent && maxDepth > 0) {
          const fun = parent[changeName]
          if (fun && typeof fun === 'function') {
            this._changeDataFunction = fun
            maxDepth = 0
            break
          }
          parent = parent.$parent
          maxDepth--
d-u-a's avatar
d-u-a 已提交
160 161
        }
      }
d-u-a's avatar
d-u-a 已提交
162
      // #endif
d-u-a's avatar
d-u-a 已提交
163

d-u-a's avatar
d-u-a 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177
      if (!this.manual) {
        this.loadData()
      }
    },
    // #ifdef H5
    beforeDestroy() {
      if (process.env.NODE_ENV === 'development' && window.unidev) {
        var cd = this._debugDataList
        var dl = window.unidev.clientDB.data
        for (var i = dl.length - 1; i >= 0; i--) {
          if (dl[i] === cd) {
            dl.splice(i, 1)
            break
          }
d-u-a's avatar
d-u-a 已提交
178 179
        }
      }
d-u-a's avatar
d-u-a 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    },
    // #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
d-u-a's avatar
d-u-a 已提交
198
        }
d-u-a's avatar
d-u-a 已提交
199 200 201 202 203 204

        this._execLoadData(callback)
      },
      loadMore() {
        if (this._isEnded) {
          return
d-u-a's avatar
d-u-a 已提交
205
        }
d-u-a's avatar
d-u-a 已提交
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
        this._execLoadData()
      },
      refresh() {
        this.clear()
        this._execLoadData()
      },
      clear() {
        this._isEnded = false
        this.dataList = []
      },
      reset() {
        this.paginationInternal.current = 1
      },
      add(value, {
        toastTitle,
        success,
        fail,
        complete
      } = {}) {
        uni.showLoading()
        let db = uniCloud.database()
        db.collection(this.collection).add(value).then((res) => {
          success && success(res)
          uni.showToast({
            title: toastTitle || '新增成功'
          })
        }).catch((err) => {
          fail && fail(err)
          uni.showModal({
            content: err.message,
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
          complete && complete()
        })
      },
      remove(id, {
        action,
        success,
        fail,
        complete,
        confirmTitle,
        confirmContent
      } = {}) {
        if (!id || !id.length) {
          return
d-u-a's avatar
d-u-a 已提交
253
        }
d-u-a's avatar
d-u-a 已提交
254 255 256 257 258 259 260 261 262
        uni.showModal({
          title: confirmTitle || '提示',
          content: confirmContent || '是否删除该数据',
          showCancel: true,
          success: (res) => {
            if (!res.confirm) {
              return
            }
            this._execRemove(id, action, success, fail, complete)
d-u-a's avatar
d-u-a 已提交
263
          }
d-u-a's avatar
d-u-a 已提交
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
        })
      },
      update(id, value, {
        toastTitle,
        success,
        fail,
        complete
      } = {}) {
        uni.showLoading()
        let db = uniCloud.database()
        return db.collection(this.collection).doc(id).update(value).then((res) => {
          success && success(res)
          uni.showToast({
            title: toastTitle || '修改成功'
          })
        }).catch((err) => {
          fail && fail(err)
          uni.showModal({
            content: err.message,
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
          complete && complete()
        })
      },
      _execLoadData(callback) {
        if (this.loading) {
          return
d-u-a's avatar
d-u-a 已提交
293
        }
d-u-a's avatar
d-u-a 已提交
294 295
        this.loading = true
        this.errorMessage = ''
d-u-a's avatar
d-u-a 已提交
296

d-u-a's avatar
d-u-a 已提交
297 298 299 300 301 302 303
        this._getExec().then((res) => {
          this.loading = false
          const {
            data,
            count
          } = res.result
          this._isEnded = data.length < this.pageSize
d-u-a's avatar
d-u-a 已提交
304

d-u-a's avatar
d-u-a 已提交
305
          const data2 = this.getone ? (data.length ? data[0] : undefined) : data
d-u-a's avatar
d-u-a 已提交
306

d-u-a's avatar
d-u-a 已提交
307 308
          callback && callback(data2, this._isEnded)
          this._dispatchEvent(events.load, data2)
309

d-u-a's avatar
d-u-a 已提交
310 311 312 313 314 315 316
          if (this.pageData === pageMode.add) {
            this.dataList.push(...data2)
            if (this.dataList.length) {
              this.paginationInternal.current++
            }
          } else {
            this.dataList = data2
d-u-a's avatar
d-u-a 已提交
317 318
          }

d-u-a's avatar
d-u-a 已提交
319 320 321
          if (this.getcount) {
            this.paginationInternal.count = count
          }
d-u-a's avatar
d-u-a 已提交
322

d-u-a's avatar
d-u-a 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
          // #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)
          if (process.env.NODE_ENV === 'development') {
            console.error(err)
          }
        })
      },
      _getExec() {
        /* eslint-disable no-undef */
        let db = uniCloud.database()
d-u-a's avatar
d-u-a 已提交
342

d-u-a's avatar
d-u-a 已提交
343 344 345
        if (this.action) {
          db = db.action(this.action)
        }
d-u-a's avatar
d-u-a 已提交
346

d-u-a's avatar
d-u-a 已提交
347
        db = db.collection(this.collection)
d-u-a's avatar
d-u-a 已提交
348

d-u-a's avatar
d-u-a 已提交
349 350 351 352 353 354 355 356 357
        if (!(!this.where || !Object.keys(this.where).length)) {
          db = db.where(this.where)
        }
        if (this.field) {
          db = db.field(this.field)
        }
        if (this.orderby) {
          db = db.orderBy(this.orderby)
        }
d-u-a's avatar
d-u-a 已提交
358

d-u-a's avatar
d-u-a 已提交
359 360 361 362 363 364 365
        const {
          current,
          size
        } = this.paginationInternal
        db = db.skip(size * (current - 1)).limit(size).get({
          getCount: this.getcount
        })
d-u-a's avatar
d-u-a 已提交
366

d-u-a's avatar
d-u-a 已提交
367 368 369 370 371 372
        return db
      },
      _execRemove(id, action, success, fail, complete) {
        if (!this.collection || !id) {
          return
        }
d-u-a's avatar
d-u-a 已提交
373

d-u-a's avatar
d-u-a 已提交
374 375 376 377
        const ids = Array.isArray(id) ? id : [id]
        if (!ids.length) {
          return
        }
d-u-a's avatar
d-u-a 已提交
378

d-u-a's avatar
d-u-a 已提交
379 380 381
        uni.showLoading({
          mask: true
        })
d-u-a's avatar
d-u-a 已提交
382

d-u-a's avatar
d-u-a 已提交
383 384 385
        /* eslint-disable no-undef */
        const db = uniCloud.database()
        const dbCmd = db.command
d-u-a's avatar
d-u-a 已提交
386

d-u-a's avatar
d-u-a 已提交
387 388 389
        let exec = db
        if (action) {
          exec = exec.action(action)
d-u-a's avatar
d-u-a 已提交
390
        }
d-u-a's avatar
d-u-a 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409

        exec.collection(this.collection).where({
          _id: dbCmd.in(ids)
        }).remove().then((res) => {
          success && success(res.result)
          if (this.pageData === pageMode.replace) {
            this.refresh()
          } else {
            this.removeData(ids)
          }
        }).catch((err) => {
          fail && fail(err)
          uni.showModal({
            content: err.message,
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
          complete && complete()
d-u-a's avatar
d-u-a 已提交
410
        })
d-u-a's avatar
d-u-a 已提交
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
      },
      removeData(ids) {
        const il = ids.slice(0)
        const dl = this.dataList
        for (let i = dl.length - 1; i >= 0; i--) {
          const 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)
d-u-a's avatar
d-u-a 已提交
428 429 430 431 432
        }
      }
    }
  }
</script>