mixin.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. module.exports = {
  2. data() {
  3. return {}
  4. },
  5. onLoad() {
  6. // getRect挂载到$u上,因为这方法需要使用in(this),所以无法把它独立成一个单独的文件导出
  7. this.$u.getRect = this.$uGetRect
  8. },
  9. methods: {
  10. // 查询节点信息
  11. // 目前此方法在支付宝小程序中无法获取组件跟接点的尺寸,为支付宝的bug(2020-07-21)
  12. // 解决办法为在组件根部再套一个没有任何作用的view元素
  13. $uGetRect(selector, all) {
  14. return new Promise(resolve => {
  15. uni.createSelectorQuery().in(this)[all ? 'selectAll' : 'select'](selector)
  16. .boundingClientRect(rect => {
  17. if (all && Array.isArray(rect) && rect.length) {
  18. resolve(rect)
  19. }
  20. if (!all && rect) {
  21. resolve(rect)
  22. }
  23. })
  24. .exec()
  25. })
  26. },
  27. getParentData(parentName = '') {
  28. // 避免在created中去定义parent变量
  29. if (!this.parent) this.parent = false;
  30. // 这里的本质原理是,通过获取父组件实例(也即u-radio-group的this)
  31. // 将父组件this中对应的参数,赋值给本组件(u-radio的this)的parentData对象中对应的属性
  32. // 之所以需要这么做,是因为所有端中,头条小程序不支持通过this.parent.xxx去监听父组件参数的变化
  33. this.parent = this.$u.$parent.call(this, parentName);
  34. if (this.parent) {
  35. // 历遍parentData中的属性,将parent中的同名属性赋值给parentData
  36. Object.keys(this.parentData).map(key => {
  37. this.parentData[key] = this.parent[key];
  38. });
  39. }
  40. },
  41. // 阻止事件冒泡
  42. preventEvent(e) {
  43. e && e.stopPropagation && e.stopPropagation()
  44. }
  45. },
  46. onReachBottom() {
  47. uni.$emit('uOnReachBottom')
  48. },
  49. beforeDestroy() {
  50. // 判断当前页面是否存在parent和chldren,一般在checkbox和checkbox-group父子联动的场景会有此情况
  51. // 组件销毁时,移除子组件在父组件children数组中的实例,释放资源,避免数据混乱
  52. if (this.parent && uni.$u.test.array(this.parent.children)) {
  53. // 组件销毁时,移除父组件中的children数组中对应的实例
  54. const childrenList = this.parent.children
  55. childrenList.map((child, index) => {
  56. // 如果相等,则移除
  57. if (child === this) {
  58. childrenList.splice(index, 1)
  59. }
  60. })
  61. }
  62. }
  63. }