'f'
mh-two-thousand-and-two
2024-04-12 26f2711ef9461961fb953e2b497bd314ef95e345
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
/**
 * 补充一些环境兼容内容,如小程序 需要使用的 selectComponent...
 * 之所以在框架内补充,而不是在 mp-runtime 中处理,是因为小程序自定义组件可能需要获取 page 对象并使用 selectComponent
 * 故, 暂时添加到所有 vm 上
 * @param {Object} Vue
 */
/**
 * 先简单支持 id 和 class
 * @param {Object} selector
 */
function parseSelector (selector) {
  if (selector.indexOf('#') === 0) {
    const id = selector.substr(1)
    return function match (vnode) {
      // props
      if (vnode.componentInstance && vnode.componentInstance.id === id) {
        return true
      }
      // attrs
      if (vnode.data && vnode.data.attrs && vnode.data.attrs.id === id) {
        return true
      }
      return false
    }
  } else if (selector.indexOf('.') === 0) {
    const clazz = selector.substr(1)
    return function match (vnode) {
      return vnode.data && matchClass(clazz, vnode.data.staticClass, vnode.data.class)
    }
  }
}
 
const CLASS_RE = /\s+/
 
function matchClass (clazz, staticClass = '', dynamicClass = '') {
  if (staticClass) {
    return staticClass.split(CLASS_RE).indexOf(clazz) !== -1
  }
  if (dynamicClass && typeof dynamicClass === 'string') {
    return dynamicClass.split(CLASS_RE).indexOf(clazz) !== -1
  }
}
 
function querySelector (vm, matchSelector) {
  if (matchSelector(vm.$vnode || vm._vnode)) {
    return vm
  }
  const $children = vm.$children
  for (let i = 0; i < $children.length; i++) {
    const childVm = querySelector($children[i], matchSelector)
    if (childVm) {
      return childVm
    }
  }
}
 
function querySelectorAll (vm, matchSelector, ret) {
  if (matchSelector(vm.$vnode || vm._vnode)) {
    ret.push(vm)
  }
  const $children = vm.$children
  for (let i = 0; i < $children.length; i++) {
    querySelectorAll($children[i], matchSelector, ret)
  }
  return ret
}
 
export function initPolyfill (Vue) {
  Vue.prototype.createIntersectionObserver = function createIntersectionObserver (options) {
    return uni.createIntersectionObserver(this, options)
  }
 
  Vue.prototype.createMediaQueryObserver = function createMediaQueryObserver (options) {
    return uni.createMediaQueryObserver(this, options)
  }
 
  Vue.prototype.selectComponent = function selectComponent (selector) {
    return querySelector(this, parseSelector(selector))
  }
 
  Vue.prototype.selectAllComponents = function selectAllComponents (selector) {
    return querySelectorAll(this, parseSelector(selector), [])
  }
}