mixin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import theme from '../config/theme.js';
  2. export default {
  3. // 定义每个组件都可能需要用到的外部样式以及类名
  4. props: {
  5. // 每个组件都有的父组件传递的样式,可以为字符串或者对象形式
  6. customStyle: {
  7. type: [Object, String],
  8. default: () => ({})
  9. },
  10. customClass: {
  11. type: [Array, String],
  12. default: ''
  13. },
  14. // 跳转的页面路径
  15. url: {
  16. type: String,
  17. default: ''
  18. },
  19. // 页面跳转的类型
  20. linkType: {
  21. type: String,
  22. default: 'navigateTo'
  23. }
  24. },
  25. data() {
  26. return {}
  27. },
  28. onLoad() {
  29. // getRect挂载到$u上,因为这方法需要使用in(this),所以无法把它独立成一个单独的文件导出
  30. this.$u.getRect = this.$uGetRect;
  31. },
  32. created() {
  33. // 组件当中,只有created声明周期,为了能在组件使用,故也在created中将方法挂载到$u
  34. this.$u.getRect = this.$uGetRect;
  35. },
  36. computed: {
  37. // 在2.x版本中,将会把$u挂载到uni对象下,导致在模板中无法使用uni.$u.xxx形式
  38. // 所以这里通过computed计算属性将其附加到this.$u上,就可以在模板或者js中使用uni.$u.xxx
  39. // 只在nvue环境通过此方式引入完整的$u,其他平台会出现性能问题,非nvue则按需引入(主要原因是props过大)
  40. $u() {
  41. // #ifndef APP-NVUE
  42. // 在非nvue端,移除props,http,mixin等对象,避免在小程序setData时数据过大影响性能
  43. return uni.$u.deepMerge(uni.$u, {
  44. props: undefined,
  45. http: undefined,
  46. mixin: undefined
  47. })
  48. // #endif
  49. // #ifdef APP-NVUE
  50. return uni.$u;
  51. // #endif
  52. },
  53. $uColor() {
  54. return (propName) => {
  55. if (this[propName] && theme.hasOwnProperty(this[propName])) {
  56. return theme[this[propName]];
  57. }
  58. return this[propName];
  59. };
  60. },
  61. /**
  62. * 生成bem规则类名
  63. * 由于微信小程序,H5,nvue之间绑定class的差异,无法通过:class="[bem()]"的形式进行同用
  64. * 故采用如下折中做法,最后返回的是数组(一般平台)或字符串(支付宝和字节跳动平台),类似['a', 'b', 'c']或'a b c'的形式
  65. * @param {String} name 组件名称
  66. * @param {Array} fixed 一直会存在的类名
  67. * @param {Array} change 会根据变量值为true或者false而出现或者隐藏的类名
  68. * @returns {Array|string}
  69. */
  70. bem() {
  71. return function (name, fixed, change) {
  72. // 类名前缀
  73. const prefix = `u-${name}--`;
  74. const classes = {};
  75. if (fixed) {
  76. fixed.map((item) => {
  77. // 这里的类名,会一直存在
  78. classes[prefix + this[item]] = true;
  79. });
  80. }
  81. if (change) {
  82. change.map((item) => {
  83. // 这里的类名,会根据this[item]的值为true或者false,而进行添加或者移除某一个类
  84. this[item] ? (classes[prefix + item] = this[item]) : (delete classes[prefix + item]);
  85. });
  86. }
  87. return Object.keys(classes)
  88. // 支付宝,头条小程序无法动态绑定一个数组类名,否则解析出来的结果会带有",",而导致失效
  89. // #ifdef MP-ALIPAY || MP-TOUTIAO || MP-LARK
  90. .join(' ');
  91. // #endif
  92. }
  93. }
  94. },
  95. methods: {
  96. // 跳转某一个页面
  97. openPage(urlKey = 'url') {
  98. const url = this[urlKey]
  99. if (url) {
  100. // 执行类似uni.navigateTo的方法
  101. uni[this.linkType]({
  102. url
  103. });
  104. }
  105. },
  106. // 查询节点信息
  107. // 目前此方法在支付宝小程序中无法获取组件跟接点的尺寸,为支付宝的bug(2020-07-21)
  108. // 解决办法为在组件根部再套一个没有任何作用的view元素
  109. $uGetRect(selector, all) {
  110. return new Promise((resolve) => {
  111. uni.createSelectorQuery()
  112. .in(this)[all ? 'selectAll' : 'select'](selector)
  113. .boundingClientRect((rect) => {
  114. if (all && Array.isArray(rect) && rect.length) {
  115. resolve(rect);
  116. }
  117. if (!all && rect) {
  118. resolve(rect);
  119. }
  120. })
  121. .exec();
  122. });
  123. },
  124. getParentData(parentName = '', nextParentName = '') {
  125. // 避免在created中去定义parent变量
  126. if (!this.parent) this.parent = {}
  127. // 这里的本质原理是,通过获取父组件实例(也即类似u-radio的父组件u-radio-group的this)
  128. // 将父组件this中对应的参数,赋值给本组件(u-radio的this)的parentData对象中对应的属性
  129. // 之所以需要这么做,是因为所有端中,头条小程序不支持通过this.parent.xxx去监听父组件参数的变化
  130. // 此处并不会自动更新子组件的数据,而是依赖父组件u-radio-group去监听data的变化,手动调用更新子组件的方法去重新获取
  131. this.parent = uni.$u.$parent.call(this, parentName);
  132. if (this.parent.children) {
  133. // 如果父组件的children不存在本组件的实例,才将本实例添加到父组件的children中
  134. this.parent.children.indexOf(this) === -1 && this.parent.children.push(this);
  135. }
  136. if (this.parent && this.parentData) {
  137. // 历遍parentData中的属性,将parent中的同名属性赋值给parentData
  138. Object.keys(this.parentData).map((key) => {
  139. this.parentData[key] = this.parent[key];
  140. });
  141. }
  142. },
  143. // 阻止事件冒泡
  144. preventEvent(e) {
  145. e && typeof (e.stopPropagation) === 'function' && e.stopPropagation();
  146. },
  147. // 空操作
  148. noop(e) {
  149. this.preventEvent(e);
  150. },
  151. // 检测即将过期的插槽并发出警告
  152. checkDeprecatedSlot(slotName, componentName, docsUrl, action = 'replace', alternative = '') {
  153. if (process.env.NODE_ENV === 'development') {
  154. if (this.$slots && this.$slots[slotName]) {
  155. let actionText = ''
  156. let recommendationText = ''
  157. if (action === 'delete') {
  158. actionText = '将被完全移除'
  159. recommendationText = '请移除该插槽的使用'
  160. } else if (action === 'replace') {
  161. actionText = '将被替代'
  162. recommendationText = alternative ? `请使用${alternative}插槽替代` : '请使用不具名插槽替代'
  163. }
  164. console.warn(
  165. `[${componentName}] ⚠️ 警告:<slot name="${slotName}"> 插槽将在后续版本中${actionText},` +
  166. `${recommendationText}。` +
  167. `\n\n` +
  168. `当前用法:` +
  169. `\n<template #${slotName}>...</template>` +
  170. `\n\n` +
  171. `推荐用法:` +
  172. `\n<${componentName}>...</${componentName}>` +
  173. `\n\n` +
  174. `更多信息请查看:${docsUrl}`
  175. )
  176. }
  177. }
  178. },
  179. // 检测即将过期的属性并发出警告
  180. checkDeprecatedProp(propName, componentName, docsUrl, action = 'replace', alternative = '') {
  181. if (process.env.NODE_ENV === 'development') {
  182. if (this[propName] !== undefined) {
  183. let actionText = ''
  184. let recommendationText = ''
  185. if (action === 'delete') {
  186. actionText = '将被完全移除'
  187. recommendationText = '请移除该属性的使用'
  188. } else if (action === 'replace') {
  189. actionText = '将被替代'
  190. recommendationText = alternative ? `请使用替代方案:${alternative}` : '请使用替代方案'
  191. }
  192. const warningMsg = `[${componentName}] ⚠️ 警告:属性 "${propName}" 将在后续版本中${actionText},` +
  193. `${recommendationText}。` +
  194. `\n\n` +
  195. `当前用法:` +
  196. `\n:${propName}="${this[propName]}"` +
  197. `\n\n`
  198. if (action === 'replace' && alternative) {
  199. console.warn(warningMsg + `推荐用法:` +
  200. `\n${alternative}` +
  201. `\n\n` +
  202. `更多信息请查看:${docsUrl}`)
  203. } else {
  204. console.warn(warningMsg + `更多信息请查看:${docsUrl}`)
  205. }
  206. }
  207. }
  208. },
  209. // 检测即将过期的事件并发出警告
  210. checkDeprecatedEvent(eventName, componentName, docsUrl, action = 'replace', alternative = '') {
  211. if (process.env.NODE_ENV === 'development') {
  212. if (this.$listeners && this.$listeners[eventName]) {
  213. let actionText = ''
  214. let recommendationText = ''
  215. if (action === 'delete') {
  216. actionText = '将被完全移除'
  217. recommendationText = '请移除该事件的使用'
  218. } else if (action === 'replace') {
  219. actionText = '将被替代'
  220. recommendationText = alternative ? `请使用替代方案:${alternative}` : '请使用替代方案'
  221. }
  222. const warningMsg = `[${componentName}] ⚠️ 警告:事件 "${eventName}" 将在后续版本中${actionText},` +
  223. `${recommendationText}。` +
  224. `\n\n` +
  225. `当前用法:` +
  226. `\n@${eventName}="handler"` +
  227. `\n\n`
  228. if (action === 'replace' && alternative) {
  229. console.warn(warningMsg + `推荐用法:` +
  230. `\n${alternative}` +
  231. `\n\n` +
  232. `更多信息请查看:${docsUrl}`)
  233. } else {
  234. console.warn(warningMsg + `更多信息请查看:${docsUrl}`)
  235. }
  236. }
  237. }
  238. },
  239. // 批量检测多个即将过期的功能
  240. checkDeprecatedFeatures(features, componentName, docsUrl) {
  241. if (process.env.NODE_ENV === 'development') {
  242. features.forEach(feature => {
  243. if (feature.type === 'slot') {
  244. this.checkDeprecatedSlot(feature.name, componentName, docsUrl, feature.action, feature.alternative)
  245. } else if (feature.type === 'prop') {
  246. this.checkDeprecatedProp(feature.name, componentName, docsUrl, feature.action, feature.alternative)
  247. } else if (feature.type === 'event') {
  248. this.checkDeprecatedEvent(feature.name, componentName, docsUrl, feature.action, feature.alternative)
  249. }
  250. })
  251. }
  252. }
  253. },
  254. onReachBottom() {
  255. uni.$emit('uOnReachBottom');
  256. },
  257. // #ifdef VUE2
  258. beforeDestroy() {
  259. // 判断当前页面是否存在parent和chldren,一般在checkbox和checkbox-group父子联动的场景会有此情况
  260. // 组件销毁时,移除子组件在父组件children数组中的实例,释放资源,避免数据混乱
  261. if (this.parent && uni.$u.test.array(this.parent.children)) {
  262. // 组件销毁时,移除子组件在父组件children数组中的实例,释放资源,避免数据混乱
  263. const childrenList = this.parent.children;
  264. childrenList.map((child, index) => {
  265. // 如果相等,则移除
  266. if (child === this) {
  267. childrenList.splice(index, 1);
  268. }
  269. });
  270. }
  271. },
  272. // #endif
  273. // #ifdef VUE3
  274. beforeUnmount() {
  275. // 判断当前页面是否存在parent和chldren,一般在checkbox和checkbox-group父子联动的场景会有此情况
  276. // 组件销毁时,移除子组件在父组件children数组中的实例,释放资源,避免数据混乱
  277. if (this.parent && uni.$u.test.array(this.parent.children)) {
  278. // 组件销毁时,移除父组件中的children数组中对应的实例
  279. const childrenList = this.parent.children;
  280. childrenList.map((child, index) => {
  281. // 如果相等,则移除
  282. if (child === this) {
  283. childrenList.splice(index, 1);
  284. }
  285. });
  286. }
  287. }
  288. // #endif
  289. }