足力健前端,vue版本

index.js 43KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823
  1. import Vue from 'vue';
  2. const _toString = Object.prototype.toString;
  3. const hasOwnProperty = Object.prototype.hasOwnProperty;
  4. function isFn (fn) {
  5. return typeof fn === 'function'
  6. }
  7. function isStr (str) {
  8. return typeof str === 'string'
  9. }
  10. function isPlainObject (obj) {
  11. return _toString.call(obj) === '[object Object]'
  12. }
  13. function hasOwn (obj, key) {
  14. return hasOwnProperty.call(obj, key)
  15. }
  16. function noop () {}
  17. /**
  18. * Create a cached version of a pure function.
  19. */
  20. function cached (fn) {
  21. const cache = Object.create(null);
  22. return function cachedFn (str) {
  23. const hit = cache[str];
  24. return hit || (cache[str] = fn(str))
  25. }
  26. }
  27. /**
  28. * Camelize a hyphen-delimited string.
  29. */
  30. const camelizeRE = /-(\w)/g;
  31. const camelize = cached((str) => {
  32. return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
  33. });
  34. const HOOKS = [
  35. 'invoke',
  36. 'success',
  37. 'fail',
  38. 'complete',
  39. 'returnValue'
  40. ];
  41. const globalInterceptors = {};
  42. const scopedInterceptors = {};
  43. function mergeHook (parentVal, childVal) {
  44. const res = childVal
  45. ? parentVal
  46. ? parentVal.concat(childVal)
  47. : Array.isArray(childVal)
  48. ? childVal : [childVal]
  49. : parentVal;
  50. return res
  51. ? dedupeHooks(res)
  52. : res
  53. }
  54. function dedupeHooks (hooks) {
  55. const res = [];
  56. for (let i = 0; i < hooks.length; i++) {
  57. if (res.indexOf(hooks[i]) === -1) {
  58. res.push(hooks[i]);
  59. }
  60. }
  61. return res
  62. }
  63. function removeHook (hooks, hook) {
  64. const index = hooks.indexOf(hook);
  65. if (index !== -1) {
  66. hooks.splice(index, 1);
  67. }
  68. }
  69. function mergeInterceptorHook (interceptor, option) {
  70. Object.keys(option).forEach(hook => {
  71. if (HOOKS.indexOf(hook) !== -1 && isFn(option[hook])) {
  72. interceptor[hook] = mergeHook(interceptor[hook], option[hook]);
  73. }
  74. });
  75. }
  76. function removeInterceptorHook (interceptor, option) {
  77. if (!interceptor || !option) {
  78. return
  79. }
  80. Object.keys(option).forEach(hook => {
  81. if (HOOKS.indexOf(hook) !== -1 && isFn(option[hook])) {
  82. removeHook(interceptor[hook], option[hook]);
  83. }
  84. });
  85. }
  86. function addInterceptor (method, option) {
  87. if (typeof method === 'string' && isPlainObject(option)) {
  88. mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), option);
  89. } else if (isPlainObject(method)) {
  90. mergeInterceptorHook(globalInterceptors, method);
  91. }
  92. }
  93. function removeInterceptor (method, option) {
  94. if (typeof method === 'string') {
  95. if (isPlainObject(option)) {
  96. removeInterceptorHook(scopedInterceptors[method], option);
  97. } else {
  98. delete scopedInterceptors[method];
  99. }
  100. } else if (isPlainObject(method)) {
  101. removeInterceptorHook(globalInterceptors, method);
  102. }
  103. }
  104. function wrapperHook (hook) {
  105. return function (data) {
  106. return hook(data) || data
  107. }
  108. }
  109. function isPromise (obj) {
  110. return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
  111. }
  112. function queue (hooks, data) {
  113. let promise = false;
  114. for (let i = 0; i < hooks.length; i++) {
  115. const hook = hooks[i];
  116. if (promise) {
  117. promise = Promise.then(wrapperHook(hook));
  118. } else {
  119. const res = hook(data);
  120. if (isPromise(res)) {
  121. promise = Promise.resolve(res);
  122. }
  123. if (res === false) {
  124. return {
  125. then () {}
  126. }
  127. }
  128. }
  129. }
  130. return promise || {
  131. then (callback) {
  132. return callback(data)
  133. }
  134. }
  135. }
  136. function wrapperOptions (interceptor, options = {}) {
  137. ['success', 'fail', 'complete'].forEach(name => {
  138. if (Array.isArray(interceptor[name])) {
  139. const oldCallback = options[name];
  140. options[name] = function callbackInterceptor (res) {
  141. queue(interceptor[name], res).then((res) => {
  142. /* eslint-disable no-mixed-operators */
  143. return isFn(oldCallback) && oldCallback(res) || res
  144. });
  145. };
  146. }
  147. });
  148. return options
  149. }
  150. function wrapperReturnValue (method, returnValue) {
  151. const returnValueHooks = [];
  152. if (Array.isArray(globalInterceptors.returnValue)) {
  153. returnValueHooks.push(...globalInterceptors.returnValue);
  154. }
  155. const interceptor = scopedInterceptors[method];
  156. if (interceptor && Array.isArray(interceptor.returnValue)) {
  157. returnValueHooks.push(...interceptor.returnValue);
  158. }
  159. returnValueHooks.forEach(hook => {
  160. returnValue = hook(returnValue) || returnValue;
  161. });
  162. return returnValue
  163. }
  164. function getApiInterceptorHooks (method) {
  165. const interceptor = Object.create(null);
  166. Object.keys(globalInterceptors).forEach(hook => {
  167. if (hook !== 'returnValue') {
  168. interceptor[hook] = globalInterceptors[hook].slice();
  169. }
  170. });
  171. const scopedInterceptor = scopedInterceptors[method];
  172. if (scopedInterceptor) {
  173. Object.keys(scopedInterceptor).forEach(hook => {
  174. if (hook !== 'returnValue') {
  175. interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
  176. }
  177. });
  178. }
  179. return interceptor
  180. }
  181. function invokeApi (method, api, options, ...params) {
  182. const interceptor = getApiInterceptorHooks(method);
  183. if (interceptor && Object.keys(interceptor).length) {
  184. if (Array.isArray(interceptor.invoke)) {
  185. const res = queue(interceptor.invoke, options);
  186. return res.then((options) => {
  187. return api(wrapperOptions(interceptor, options), ...params)
  188. })
  189. } else {
  190. return api(wrapperOptions(interceptor, options), ...params)
  191. }
  192. }
  193. return api(options, ...params)
  194. }
  195. const promiseInterceptor = {
  196. returnValue (res) {
  197. if (!isPromise(res)) {
  198. return res
  199. }
  200. return res.then(res => {
  201. return res[1]
  202. }).catch(res => {
  203. return res[0]
  204. })
  205. }
  206. };
  207. const SYNC_API_RE =
  208. /^\$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/;
  209. const CONTEXT_API_RE = /^create|Manager$/;
  210. // Context例外情况
  211. const CONTEXT_API_RE_EXC = ['createBLEConnection'];
  212. // 同步例外情况
  213. const ASYNC_API = ['createBLEConnection'];
  214. const CALLBACK_API_RE = /^on|^off/;
  215. function isContextApi (name) {
  216. return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1
  217. }
  218. function isSyncApi (name) {
  219. return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1
  220. }
  221. function isCallbackApi (name) {
  222. return CALLBACK_API_RE.test(name) && name !== 'onPush'
  223. }
  224. function handlePromise (promise) {
  225. return promise.then(data => {
  226. return [null, data]
  227. })
  228. .catch(err => [err])
  229. }
  230. function shouldPromise (name) {
  231. if (
  232. isContextApi(name) ||
  233. isSyncApi(name) ||
  234. isCallbackApi(name)
  235. ) {
  236. return false
  237. }
  238. return true
  239. }
  240. /* eslint-disable no-extend-native */
  241. if (!Promise.prototype.finally) {
  242. Promise.prototype.finally = function (callback) {
  243. const promise = this.constructor;
  244. return this.then(
  245. value => promise.resolve(callback()).then(() => value),
  246. reason => promise.resolve(callback()).then(() => {
  247. throw reason
  248. })
  249. )
  250. };
  251. }
  252. function promisify (name, api) {
  253. if (!shouldPromise(name)) {
  254. return api
  255. }
  256. return function promiseApi (options = {}, ...params) {
  257. if (isFn(options.success) || isFn(options.fail) || isFn(options.complete)) {
  258. return wrapperReturnValue(name, invokeApi(name, api, options, ...params))
  259. }
  260. return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
  261. invokeApi(name, api, Object.assign({}, options, {
  262. success: resolve,
  263. fail: reject
  264. }), ...params);
  265. })))
  266. }
  267. }
  268. const EPS = 1e-4;
  269. const BASE_DEVICE_WIDTH = 750;
  270. let isIOS = false;
  271. let deviceWidth = 0;
  272. let deviceDPR = 0;
  273. function checkDeviceWidth () {
  274. const {
  275. platform,
  276. pixelRatio,
  277. windowWidth
  278. } = tt.getSystemInfoSync(); // uni=>tt runtime 编译目标是 uni 对象,内部不允许直接使用 uni
  279. deviceWidth = windowWidth;
  280. deviceDPR = pixelRatio;
  281. isIOS = platform === 'ios';
  282. }
  283. function upx2px (number, newDeviceWidth) {
  284. if (deviceWidth === 0) {
  285. checkDeviceWidth();
  286. }
  287. number = Number(number);
  288. if (number === 0) {
  289. return 0
  290. }
  291. let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth);
  292. if (result < 0) {
  293. result = -result;
  294. }
  295. result = Math.floor(result + EPS);
  296. if (result === 0) {
  297. if (deviceDPR === 1 || !isIOS) {
  298. return 1
  299. } else {
  300. return 0.5
  301. }
  302. }
  303. return number < 0 ? -result : result
  304. }
  305. const interceptors = {
  306. promiseInterceptor
  307. };
  308. var baseApi = /*#__PURE__*/Object.freeze({
  309. __proto__: null,
  310. upx2px: upx2px,
  311. addInterceptor: addInterceptor,
  312. removeInterceptor: removeInterceptor,
  313. interceptors: interceptors
  314. });
  315. var previewImage = {
  316. args (fromArgs) {
  317. let currentIndex = parseInt(fromArgs.current);
  318. if (isNaN(currentIndex)) {
  319. return
  320. }
  321. const urls = fromArgs.urls;
  322. if (!Array.isArray(urls)) {
  323. return
  324. }
  325. const len = urls.length;
  326. if (!len) {
  327. return
  328. }
  329. if (currentIndex < 0) {
  330. currentIndex = 0;
  331. } else if (currentIndex >= len) {
  332. currentIndex = len - 1;
  333. }
  334. if (currentIndex > 0) {
  335. fromArgs.current = urls[currentIndex];
  336. fromArgs.urls = urls.filter(
  337. (item, index) => index < currentIndex ? item !== urls[currentIndex] : true
  338. );
  339. } else {
  340. fromArgs.current = urls[0];
  341. }
  342. return {
  343. indicator: false,
  344. loop: false
  345. }
  346. }
  347. };
  348. // 不支持的 API 列表
  349. const todos = [
  350. // 'createCameraContext',
  351. // 'createLivePlayerContext',
  352. // 'getSavedFileInfo',
  353. // 'createMapContext',
  354. // 'onMemoryWarning',
  355. // 'onGyroscopeChange',
  356. // 'startGyroscope',
  357. // 'stopGyroscope',
  358. // 'setScreenBrightness',
  359. // 'getScreenBrightness',
  360. // 'addPhoneContact',
  361. // 'openBluetoothAdapter',
  362. // 'startBluetoothDevicesDiscovery',
  363. // 'onBluetoothDeviceFound',
  364. // 'stopBluetoothDevicesDiscovery',
  365. // 'onBluetoothAdapterStateChange',
  366. // 'getConnectedBluetoothDevices',
  367. // 'getBluetoothDevices',
  368. // 'getBluetoothAdapterState',
  369. // 'closeBluetoothAdapter',
  370. // 'writeBLECharacteristicValue',
  371. // 'readBLECharacteristicValue',
  372. // 'onBLEConnectionStateChange',
  373. // 'onBLECharacteristicValueChange',
  374. // 'notifyBLECharacteristicValueChange',
  375. // 'getBLEDeviceServices',
  376. // 'getBLEDeviceCharacteristics',
  377. // 'createBLEConnection',
  378. // 'closeBLEConnection',
  379. // 'onBeaconServiceChange',
  380. // 'onBeaconUpdate',
  381. // 'getBeacons',
  382. // 'startBeaconDiscovery',
  383. // 'stopBeaconDiscovery',
  384. // 'showNavigationBarLoading',
  385. // 'hideNavigationBarLoading',
  386. // 'setTabBarItem',
  387. // 'setTabBarStyle',
  388. // 'hideTabBar',
  389. // 'showTabBar',
  390. // 'setTabBarBadge',
  391. // 'removeTabBarBadge',
  392. // 'showTabBarRedDot',
  393. // 'hideTabBarRedDot',
  394. // 'setBackgroundColor',
  395. // 'setBackgroundTextStyle',
  396. // 'chooseInvoiceTitle',
  397. // 'addTemplate',
  398. // 'deleteTemplate',
  399. // 'getTemplateLibraryById',
  400. // 'getTemplateLibraryList',
  401. // 'getTemplateList',
  402. // 'sendTemplateMessage',
  403. // 'setEnableDebug',
  404. // 'onWindowResize',
  405. // 'offWindowResize',
  406. // 'createOffscreenCanvas',
  407. // 'vibrate'
  408. ];
  409. // 存在兼容性的 API 列表
  410. // 头条小程序自1.35.0+支持canIUses
  411. const canIUses = [
  412. // 'createIntersectionObserver',
  413. // 'getSavedFileList',
  414. // 'removeSavedFile',
  415. // 'hideKeyboard',
  416. // 'getImageInfo',
  417. // 'createVideoContext',
  418. // 'onSocketOpen',
  419. // 'onSocketError',
  420. // 'sendSocketMessage',
  421. // 'onSocketMessage',
  422. // 'closeSocket',
  423. // 'onSocketClose',
  424. // 'getExtConfig',
  425. // 'getExtConfigSync',
  426. // 'navigateToMiniProgram',
  427. // 'navigateBackMiniProgram',
  428. // 'compressImage',
  429. // 'chooseLocation',
  430. // 'openDocument',
  431. // 'onUserCaptureScreen',
  432. // 'getBackgroundAudioManager',
  433. // 'setNavigationBarColor',
  434. ];
  435. // 需要做转换的 API 列表
  436. const protocols = {
  437. chooseImage: {
  438. args: {
  439. sizeType: false
  440. }
  441. },
  442. previewImage,
  443. connectSocket: {
  444. args: {
  445. method: false
  446. }
  447. },
  448. chooseVideo: {
  449. args: {
  450. camera: false
  451. }
  452. },
  453. scanCode: {
  454. args: {
  455. onlyFromCamera: false,
  456. scanType: false
  457. }
  458. },
  459. startAccelerometer: {
  460. args: {
  461. interval: false
  462. }
  463. },
  464. showToast: {
  465. args: {
  466. image: false,
  467. mask: false
  468. }
  469. },
  470. showLoading: {
  471. args: {
  472. mask: false
  473. }
  474. },
  475. showModal: {
  476. args: {
  477. cancelColor: false,
  478. confirmColor: false
  479. }
  480. },
  481. showActionSheet: {
  482. args: {
  483. itemColor: false
  484. }
  485. },
  486. login: {
  487. args: {
  488. scopes: false,
  489. timeout: false
  490. }
  491. },
  492. getUserInfo: {
  493. args: {
  494. lang: false,
  495. timeout: false
  496. }
  497. },
  498. requestPayment: {
  499. name: tt.pay ? 'pay' : 'requestPayment',
  500. args: {
  501. orderInfo: tt.pay ? 'orderInfo' : 'data'
  502. }
  503. },
  504. getFileInfo: {
  505. args: {
  506. digestAlgorithm: false
  507. }
  508. }
  509. };
  510. const CALLBACKS = ['success', 'fail', 'cancel', 'complete'];
  511. function processCallback (methodName, method, returnValue) {
  512. return function (res) {
  513. return method(processReturnValue(methodName, res, returnValue))
  514. }
  515. }
  516. function processArgs (methodName, fromArgs, argsOption = {}, returnValue = {}, keepFromArgs = false) {
  517. if (isPlainObject(fromArgs)) { // 一般 api 的参数解析
  518. const toArgs = keepFromArgs === true ? fromArgs : {}; // returnValue 为 false 时,说明是格式化返回值,直接在返回值对象上修改赋值
  519. if (isFn(argsOption)) {
  520. argsOption = argsOption(fromArgs, toArgs) || {};
  521. }
  522. for (const key in fromArgs) {
  523. if (hasOwn(argsOption, key)) {
  524. let keyOption = argsOption[key];
  525. if (isFn(keyOption)) {
  526. keyOption = keyOption(fromArgs[key], fromArgs, toArgs);
  527. }
  528. if (!keyOption) { // 不支持的参数
  529. console.warn(`头条小程序 ${methodName}暂不支持${key}`);
  530. } else if (isStr(keyOption)) { // 重写参数 key
  531. toArgs[keyOption] = fromArgs[key];
  532. } else if (isPlainObject(keyOption)) { // {name:newName,value:value}可重新指定参数 key:value
  533. toArgs[keyOption.name ? keyOption.name : key] = keyOption.value;
  534. }
  535. } else if (CALLBACKS.indexOf(key) !== -1) {
  536. toArgs[key] = processCallback(methodName, fromArgs[key], returnValue);
  537. } else {
  538. if (!keepFromArgs) {
  539. toArgs[key] = fromArgs[key];
  540. }
  541. }
  542. }
  543. return toArgs
  544. } else if (isFn(fromArgs)) {
  545. fromArgs = processCallback(methodName, fromArgs, returnValue);
  546. }
  547. return fromArgs
  548. }
  549. function processReturnValue (methodName, res, returnValue, keepReturnValue = false) {
  550. if (isFn(protocols.returnValue)) { // 处理通用 returnValue
  551. res = protocols.returnValue(methodName, res);
  552. }
  553. return processArgs(methodName, res, returnValue, {}, keepReturnValue)
  554. }
  555. function wrapper (methodName, method) {
  556. if (hasOwn(protocols, methodName)) {
  557. const protocol = protocols[methodName];
  558. if (!protocol) { // 暂不支持的 api
  559. return function () {
  560. console.error(`头条小程序 暂不支持${methodName}`);
  561. }
  562. }
  563. return function (arg1, arg2) { // 目前 api 最多两个参数
  564. let options = protocol;
  565. if (isFn(protocol)) {
  566. options = protocol(arg1);
  567. }
  568. arg1 = processArgs(methodName, arg1, options.args, options.returnValue);
  569. const args = [arg1];
  570. if (typeof arg2 !== 'undefined') {
  571. args.push(arg2);
  572. }
  573. const returnValue = tt[options.name || methodName].apply(tt, args);
  574. if (isSyncApi(methodName)) { // 同步 api
  575. return processReturnValue(methodName, returnValue, options.returnValue, isContextApi(methodName))
  576. }
  577. return returnValue
  578. }
  579. }
  580. return method
  581. }
  582. const todoApis = Object.create(null);
  583. const TODOS = [
  584. 'onTabBarMidButtonTap',
  585. 'subscribePush',
  586. 'unsubscribePush',
  587. 'onPush',
  588. 'offPush',
  589. 'share'
  590. ];
  591. function createTodoApi (name) {
  592. return function todoApi ({
  593. fail,
  594. complete
  595. }) {
  596. const res = {
  597. errMsg: `${name}:fail:暂不支持 ${name} 方法`
  598. };
  599. isFn(fail) && fail(res);
  600. isFn(complete) && complete(res);
  601. }
  602. }
  603. TODOS.forEach(function (name) {
  604. todoApis[name] = createTodoApi(name);
  605. });
  606. var providers = {
  607. oauth: ['toutiao'],
  608. share: ['toutiao'],
  609. payment: ['toutiao'],
  610. push: ['toutiao']
  611. };
  612. function getProvider ({
  613. service,
  614. success,
  615. fail,
  616. complete
  617. }) {
  618. let res = false;
  619. if (providers[service]) {
  620. res = {
  621. errMsg: 'getProvider:ok',
  622. service,
  623. provider: providers[service]
  624. };
  625. isFn(success) && success(res);
  626. } else {
  627. res = {
  628. errMsg: 'getProvider:fail:服务[' + service + ']不存在'
  629. };
  630. isFn(fail) && fail(res);
  631. }
  632. isFn(complete) && complete(res);
  633. }
  634. var extraApi = /*#__PURE__*/Object.freeze({
  635. __proto__: null,
  636. getProvider: getProvider
  637. });
  638. const getEmitter = (function () {
  639. if (typeof getUniEmitter === 'function') {
  640. /* eslint-disable no-undef */
  641. return getUniEmitter
  642. }
  643. let Emitter;
  644. return function getUniEmitter () {
  645. if (!Emitter) {
  646. Emitter = new Vue();
  647. }
  648. return Emitter
  649. }
  650. })();
  651. function apply (ctx, method, args) {
  652. return ctx[method].apply(ctx, args)
  653. }
  654. function $on () {
  655. return apply(getEmitter(), '$on', [...arguments])
  656. }
  657. function $off () {
  658. return apply(getEmitter(), '$off', [...arguments])
  659. }
  660. function $once () {
  661. return apply(getEmitter(), '$once', [...arguments])
  662. }
  663. function $emit () {
  664. return apply(getEmitter(), '$emit', [...arguments])
  665. }
  666. var eventApi = /*#__PURE__*/Object.freeze({
  667. __proto__: null,
  668. $on: $on,
  669. $off: $off,
  670. $once: $once,
  671. $emit: $emit
  672. });
  673. var api = /*#__PURE__*/Object.freeze({
  674. __proto__: null
  675. });
  676. const MPPage = Page;
  677. const MPComponent = Component;
  678. const customizeRE = /:/g;
  679. const customize = cached((str) => {
  680. return camelize(str.replace(customizeRE, '-'))
  681. });
  682. function initTriggerEvent (mpInstance) {
  683. const oldTriggerEvent = mpInstance.triggerEvent;
  684. mpInstance.triggerEvent = function (event, ...args) {
  685. return oldTriggerEvent.apply(mpInstance, [customize(event), ...args])
  686. };
  687. }
  688. function initHook (name, options) {
  689. const oldHook = options[name];
  690. if (!oldHook) {
  691. options[name] = function () {
  692. initTriggerEvent(this);
  693. };
  694. } else {
  695. options[name] = function (...args) {
  696. initTriggerEvent(this);
  697. return oldHook.apply(this, args)
  698. };
  699. }
  700. }
  701. Page = function (options = {}) {
  702. initHook('onLoad', options);
  703. return MPPage(options)
  704. };
  705. Component = function (options = {}) {
  706. initHook('created', options);
  707. return MPComponent(options)
  708. };
  709. const PAGE_EVENT_HOOKS = [
  710. 'onPullDownRefresh',
  711. 'onReachBottom',
  712. 'onShareAppMessage',
  713. 'onPageScroll',
  714. 'onResize',
  715. 'onTabItemTap'
  716. ];
  717. function initMocks (vm, mocks) {
  718. const mpInstance = vm.$mp[vm.mpType];
  719. mocks.forEach(mock => {
  720. if (hasOwn(mpInstance, mock)) {
  721. vm[mock] = mpInstance[mock];
  722. }
  723. });
  724. }
  725. function hasHook (hook, vueOptions) {
  726. if (!vueOptions) {
  727. return true
  728. }
  729. if (Vue.options && Array.isArray(Vue.options[hook])) {
  730. return true
  731. }
  732. vueOptions = vueOptions.default || vueOptions;
  733. if (isFn(vueOptions)) {
  734. if (isFn(vueOptions.extendOptions[hook])) {
  735. return true
  736. }
  737. if (vueOptions.super &&
  738. vueOptions.super.options &&
  739. Array.isArray(vueOptions.super.options[hook])) {
  740. return true
  741. }
  742. return false
  743. }
  744. if (isFn(vueOptions[hook])) {
  745. return true
  746. }
  747. const mixins = vueOptions.mixins;
  748. if (Array.isArray(mixins)) {
  749. return !!mixins.find(mixin => hasHook(hook, mixin))
  750. }
  751. }
  752. function initHooks (mpOptions, hooks, vueOptions) {
  753. hooks.forEach(hook => {
  754. if (hasHook(hook, vueOptions)) {
  755. mpOptions[hook] = function (args) {
  756. return this.$vm && this.$vm.__call_hook(hook, args)
  757. };
  758. }
  759. });
  760. }
  761. function initVueComponent (Vue, vueOptions) {
  762. vueOptions = vueOptions.default || vueOptions;
  763. let VueComponent;
  764. if (isFn(vueOptions)) {
  765. VueComponent = vueOptions;
  766. } else {
  767. VueComponent = Vue.extend(vueOptions);
  768. }
  769. vueOptions = VueComponent.options;
  770. return [VueComponent, vueOptions]
  771. }
  772. function initSlots (vm, vueSlots) {
  773. if (Array.isArray(vueSlots) && vueSlots.length) {
  774. const $slots = Object.create(null);
  775. vueSlots.forEach(slotName => {
  776. $slots[slotName] = true;
  777. });
  778. vm.$scopedSlots = vm.$slots = $slots;
  779. }
  780. }
  781. function initVueIds (vueIds, mpInstance) {
  782. vueIds = (vueIds || '').split(',');
  783. const len = vueIds.length;
  784. if (len === 1) {
  785. mpInstance._$vueId = vueIds[0];
  786. } else if (len === 2) {
  787. mpInstance._$vueId = vueIds[0];
  788. mpInstance._$vuePid = vueIds[1];
  789. }
  790. }
  791. function initData (vueOptions, context) {
  792. let data = vueOptions.data || {};
  793. const methods = vueOptions.methods || {};
  794. if (typeof data === 'function') {
  795. try {
  796. data = data.call(context); // 支持 Vue.prototype 上挂的数据
  797. } catch (e) {
  798. if (process.env.VUE_APP_DEBUG) {
  799. console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data);
  800. }
  801. }
  802. } else {
  803. try {
  804. // 对 data 格式化
  805. data = JSON.parse(JSON.stringify(data));
  806. } catch (e) {}
  807. }
  808. if (!isPlainObject(data)) {
  809. data = {};
  810. }
  811. Object.keys(methods).forEach(methodName => {
  812. if (context.__lifecycle_hooks__.indexOf(methodName) === -1 && !hasOwn(data, methodName)) {
  813. data[methodName] = methods[methodName];
  814. }
  815. });
  816. return data
  817. }
  818. const PROP_TYPES = [String, Number, Boolean, Object, Array, null];
  819. function createObserver (name) {
  820. return function observer (newVal, oldVal) {
  821. if (this.$vm) {
  822. this.$vm[name] = newVal; // 为了触发其他非 render watcher
  823. }
  824. }
  825. }
  826. function initBehaviors (vueOptions, initBehavior) {
  827. const vueBehaviors = vueOptions.behaviors;
  828. const vueExtends = vueOptions.extends;
  829. const vueMixins = vueOptions.mixins;
  830. let vueProps = vueOptions.props;
  831. if (!vueProps) {
  832. vueOptions.props = vueProps = [];
  833. }
  834. const behaviors = [];
  835. if (Array.isArray(vueBehaviors)) {
  836. vueBehaviors.forEach(behavior => {
  837. behaviors.push(behavior.replace('uni://', `${"tt"}://`));
  838. if (behavior === 'uni://form-field') {
  839. if (Array.isArray(vueProps)) {
  840. vueProps.push('name');
  841. vueProps.push('value');
  842. } else {
  843. vueProps.name = {
  844. type: String,
  845. default: ''
  846. };
  847. vueProps.value = {
  848. type: [String, Number, Boolean, Array, Object, Date],
  849. default: ''
  850. };
  851. }
  852. }
  853. });
  854. }
  855. if (isPlainObject(vueExtends) && vueExtends.props) {
  856. behaviors.push(
  857. initBehavior({
  858. properties: initProperties(vueExtends.props, true)
  859. })
  860. );
  861. }
  862. if (Array.isArray(vueMixins)) {
  863. vueMixins.forEach(vueMixin => {
  864. if (isPlainObject(vueMixin) && vueMixin.props) {
  865. behaviors.push(
  866. initBehavior({
  867. properties: initProperties(vueMixin.props, true)
  868. })
  869. );
  870. }
  871. });
  872. }
  873. return behaviors
  874. }
  875. function parsePropType (key, type, defaultValue, file) {
  876. // [String]=>String
  877. if (Array.isArray(type) && type.length === 1) {
  878. return type[0]
  879. }
  880. return type
  881. }
  882. function initProperties (props, isBehavior = false, file = '') {
  883. const properties = {};
  884. if (!isBehavior) {
  885. properties.vueId = {
  886. type: String,
  887. value: ''
  888. };
  889. properties.vueSlots = { // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots
  890. type: null,
  891. value: [],
  892. observer: function (newVal, oldVal) {
  893. const $slots = Object.create(null);
  894. newVal.forEach(slotName => {
  895. $slots[slotName] = true;
  896. });
  897. this.setData({
  898. $slots
  899. });
  900. }
  901. };
  902. }
  903. if (Array.isArray(props)) { // ['title']
  904. props.forEach(key => {
  905. properties[key] = {
  906. type: null,
  907. observer: createObserver(key)
  908. };
  909. });
  910. } else if (isPlainObject(props)) { // {title:{type:String,default:''},content:String}
  911. Object.keys(props).forEach(key => {
  912. const opts = props[key];
  913. if (isPlainObject(opts)) { // title:{type:String,default:''}
  914. let value = opts.default;
  915. if (isFn(value)) {
  916. value = value();
  917. }
  918. opts.type = parsePropType(key, opts.type);
  919. properties[key] = {
  920. type: PROP_TYPES.indexOf(opts.type) !== -1 ? opts.type : null,
  921. value,
  922. observer: createObserver(key)
  923. };
  924. } else { // content:String
  925. const type = parsePropType(key, opts);
  926. properties[key] = {
  927. type: PROP_TYPES.indexOf(type) !== -1 ? type : null,
  928. observer: createObserver(key)
  929. };
  930. }
  931. });
  932. }
  933. return properties
  934. }
  935. function wrapper$1 (event) {
  936. // TODO 又得兼容 mpvue 的 mp 对象
  937. try {
  938. event.mp = JSON.parse(JSON.stringify(event));
  939. } catch (e) {}
  940. event.stopPropagation = noop;
  941. event.preventDefault = noop;
  942. event.target = event.target || {};
  943. if (!hasOwn(event, 'detail')) {
  944. event.detail = {};
  945. }
  946. if (hasOwn(event, 'markerId')) {
  947. event.detail = typeof event.detail === 'object' ? event.detail : {};
  948. event.detail.markerId = event.markerId;
  949. }
  950. if (isPlainObject(event.detail)) {
  951. event.target = Object.assign({}, event.target, event.detail);
  952. }
  953. return event
  954. }
  955. function getExtraValue (vm, dataPathsArray) {
  956. let context = vm;
  957. dataPathsArray.forEach(dataPathArray => {
  958. const dataPath = dataPathArray[0];
  959. const value = dataPathArray[2];
  960. if (dataPath || typeof value !== 'undefined') { // ['','',index,'disable']
  961. const propPath = dataPathArray[1];
  962. const valuePath = dataPathArray[3];
  963. const vFor = dataPath ? vm.__get_value(dataPath, context) : context;
  964. if (Number.isInteger(vFor)) {
  965. context = value;
  966. } else if (!propPath) {
  967. context = vFor[value];
  968. } else {
  969. if (Array.isArray(vFor)) {
  970. context = vFor.find(vForItem => {
  971. return vm.__get_value(propPath, vForItem) === value
  972. });
  973. } else if (isPlainObject(vFor)) {
  974. context = Object.keys(vFor).find(vForKey => {
  975. return vm.__get_value(propPath, vFor[vForKey]) === value
  976. });
  977. } else {
  978. console.error('v-for 暂不支持循环数据:', vFor);
  979. }
  980. }
  981. if (valuePath) {
  982. context = vm.__get_value(valuePath, context);
  983. }
  984. }
  985. });
  986. return context
  987. }
  988. function processEventExtra (vm, extra, event) {
  989. const extraObj = {};
  990. if (Array.isArray(extra) && extra.length) {
  991. /**
  992. *[
  993. * ['data.items', 'data.id', item.data.id],
  994. * ['metas', 'id', meta.id]
  995. *],
  996. *[
  997. * ['data.items', 'data.id', item.data.id],
  998. * ['metas', 'id', meta.id]
  999. *],
  1000. *'test'
  1001. */
  1002. extra.forEach((dataPath, index) => {
  1003. if (typeof dataPath === 'string') {
  1004. if (!dataPath) { // model,prop.sync
  1005. extraObj['$' + index] = vm;
  1006. } else {
  1007. if (dataPath === '$event') { // $event
  1008. extraObj['$' + index] = event;
  1009. } else if (dataPath.indexOf('$event.') === 0) { // $event.target.value
  1010. extraObj['$' + index] = vm.__get_value(dataPath.replace('$event.', ''), event);
  1011. } else {
  1012. extraObj['$' + index] = vm.__get_value(dataPath);
  1013. }
  1014. }
  1015. } else {
  1016. extraObj['$' + index] = getExtraValue(vm, dataPath);
  1017. }
  1018. });
  1019. }
  1020. return extraObj
  1021. }
  1022. function getObjByArray (arr) {
  1023. const obj = {};
  1024. for (let i = 1; i < arr.length; i++) {
  1025. const element = arr[i];
  1026. obj[element[0]] = element[1];
  1027. }
  1028. return obj
  1029. }
  1030. function processEventArgs (vm, event, args = [], extra = [], isCustom, methodName) {
  1031. let isCustomMPEvent = false; // wxcomponent 组件,传递原始 event 对象
  1032. if (isCustom) { // 自定义事件
  1033. isCustomMPEvent = event.currentTarget &&
  1034. event.currentTarget.dataset &&
  1035. event.currentTarget.dataset.comType === 'wx';
  1036. if (!args.length) { // 无参数,直接传入 event 或 detail 数组
  1037. if (isCustomMPEvent) {
  1038. return [event]
  1039. }
  1040. return event.detail.__args__ || event.detail
  1041. }
  1042. }
  1043. const extraObj = processEventExtra(vm, extra, event);
  1044. const ret = [];
  1045. args.forEach(arg => {
  1046. if (arg === '$event') {
  1047. if (methodName === '__set_model' && !isCustom) { // input v-model value
  1048. ret.push(event.target.value);
  1049. } else {
  1050. if (isCustom && !isCustomMPEvent) {
  1051. ret.push(event.detail.__args__[0]);
  1052. } else { // wxcomponent 组件或内置组件
  1053. ret.push(event);
  1054. }
  1055. }
  1056. } else {
  1057. if (Array.isArray(arg) && arg[0] === 'o') {
  1058. ret.push(getObjByArray(arg));
  1059. } else if (typeof arg === 'string' && hasOwn(extraObj, arg)) {
  1060. ret.push(extraObj[arg]);
  1061. } else {
  1062. ret.push(arg);
  1063. }
  1064. }
  1065. });
  1066. return ret
  1067. }
  1068. const ONCE = '~';
  1069. const CUSTOM = '^';
  1070. function isMatchEventType (eventType, optType) {
  1071. return (eventType === optType) ||
  1072. (
  1073. optType === 'regionchange' &&
  1074. (
  1075. eventType === 'begin' ||
  1076. eventType === 'end'
  1077. )
  1078. )
  1079. }
  1080. function handleEvent (event) {
  1081. event = wrapper$1(event);
  1082. // [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]]
  1083. const dataset = (event.currentTarget || event.target).dataset;
  1084. if (!dataset) {
  1085. return console.warn('事件信息不存在')
  1086. }
  1087. const eventOpts = dataset.eventOpts || dataset['event-opts']; // 支付宝 web-view 组件 dataset 非驼峰
  1088. if (!eventOpts) {
  1089. return console.warn('事件信息不存在')
  1090. }
  1091. // [['handle',[1,2,a]],['handle1',[1,2,a]]]
  1092. const eventType = event.type;
  1093. const ret = [];
  1094. eventOpts.forEach(eventOpt => {
  1095. let type = eventOpt[0];
  1096. const eventsArray = eventOpt[1];
  1097. const isCustom = type.charAt(0) === CUSTOM;
  1098. type = isCustom ? type.slice(1) : type;
  1099. const isOnce = type.charAt(0) === ONCE;
  1100. type = isOnce ? type.slice(1) : type;
  1101. if (eventsArray && isMatchEventType(eventType, type)) {
  1102. eventsArray.forEach(eventArray => {
  1103. const methodName = eventArray[0];
  1104. if (methodName) {
  1105. let handlerCtx = this.$vm;
  1106. if (
  1107. handlerCtx.$options.generic &&
  1108. handlerCtx.$parent &&
  1109. handlerCtx.$parent.$parent
  1110. ) { // mp-weixin,mp-toutiao 抽象节点模拟 scoped slots
  1111. handlerCtx = handlerCtx.$parent.$parent;
  1112. }
  1113. if (methodName === '$emit') {
  1114. handlerCtx.$emit.apply(handlerCtx,
  1115. processEventArgs(
  1116. this.$vm,
  1117. event,
  1118. eventArray[1],
  1119. eventArray[2],
  1120. isCustom,
  1121. methodName
  1122. ));
  1123. return
  1124. }
  1125. const handler = handlerCtx[methodName];
  1126. if (!isFn(handler)) {
  1127. throw new Error(` _vm.${methodName} is not a function`)
  1128. }
  1129. if (isOnce) {
  1130. if (handler.once) {
  1131. return
  1132. }
  1133. handler.once = true;
  1134. }
  1135. ret.push(handler.apply(handlerCtx, processEventArgs(
  1136. this.$vm,
  1137. event,
  1138. eventArray[1],
  1139. eventArray[2],
  1140. isCustom,
  1141. methodName
  1142. )));
  1143. }
  1144. });
  1145. }
  1146. });
  1147. if (
  1148. eventType === 'input' &&
  1149. ret.length === 1 &&
  1150. typeof ret[0] !== 'undefined'
  1151. ) {
  1152. return ret[0]
  1153. }
  1154. }
  1155. const hooks = [
  1156. 'onShow',
  1157. 'onHide',
  1158. 'onError',
  1159. 'onPageNotFound'
  1160. ];
  1161. function parseBaseApp (vm, {
  1162. mocks,
  1163. initRefs
  1164. }) {
  1165. if (vm.$options.store) {
  1166. Vue.prototype.$store = vm.$options.store;
  1167. }
  1168. Vue.prototype.mpHost = "mp-toutiao";
  1169. Vue.mixin({
  1170. beforeCreate () {
  1171. if (!this.$options.mpType) {
  1172. return
  1173. }
  1174. this.mpType = this.$options.mpType;
  1175. this.$mp = {
  1176. data: {},
  1177. [this.mpType]: this.$options.mpInstance
  1178. };
  1179. this.$scope = this.$options.mpInstance;
  1180. delete this.$options.mpType;
  1181. delete this.$options.mpInstance;
  1182. if (this.mpType !== 'app') {
  1183. initRefs(this);
  1184. initMocks(this, mocks);
  1185. }
  1186. }
  1187. });
  1188. const appOptions = {
  1189. onLaunch (args) {
  1190. if (this.$vm) { // 已经初始化过了,主要是为了百度,百度 onShow 在 onLaunch 之前
  1191. return
  1192. }
  1193. this.$vm = vm;
  1194. this.$vm.$mp = {
  1195. app: this
  1196. };
  1197. this.$vm.$scope = this;
  1198. // vm 上也挂载 globalData
  1199. this.$vm.globalData = this.globalData;
  1200. this.$vm._isMounted = true;
  1201. this.$vm.__call_hook('mounted', args);
  1202. this.$vm.__call_hook('onLaunch', args);
  1203. }
  1204. };
  1205. // 兼容旧版本 globalData
  1206. appOptions.globalData = vm.$options.globalData || {};
  1207. // 将 methods 中的方法挂在 getApp() 中
  1208. const methods = vm.$options.methods;
  1209. if (methods) {
  1210. Object.keys(methods).forEach(name => {
  1211. appOptions[name] = methods[name];
  1212. });
  1213. }
  1214. initHooks(appOptions, hooks);
  1215. return appOptions
  1216. }
  1217. function findVmByVueId (vm, vuePid) {
  1218. const $children = vm.$children;
  1219. // 优先查找直属(反向查找:https://github.com/dcloudio/uni-app/issues/1200)
  1220. for (let i = $children.length - 1; i >= 0; i--) {
  1221. const childVm = $children[i];
  1222. if (childVm.$scope._$vueId === vuePid) {
  1223. return childVm
  1224. }
  1225. }
  1226. // 反向递归查找
  1227. let parentVm;
  1228. for (let i = $children.length - 1; i >= 0; i--) {
  1229. parentVm = findVmByVueId($children[i], vuePid);
  1230. if (parentVm) {
  1231. return parentVm
  1232. }
  1233. }
  1234. }
  1235. function initBehavior (options) {
  1236. return Behavior(options)
  1237. }
  1238. function handleLink (event) {
  1239. const {
  1240. vuePid,
  1241. vueOptions
  1242. } = event.detail || event.value; // detail 是微信,value 是百度(dipatch)
  1243. let parentVm;
  1244. if (vuePid) {
  1245. parentVm = findVmByVueId(this.$vm, vuePid);
  1246. }
  1247. if (!parentVm) {
  1248. parentVm = this.$vm;
  1249. }
  1250. vueOptions.parent = parentVm;
  1251. }
  1252. const mocks = ['__route__', '__webviewId__', '__nodeid__', '__nodeId__'];
  1253. function isPage () {
  1254. return this.__nodeid__ === 0 || this.__nodeId__ === 0
  1255. }
  1256. function initRefs (vm) {
  1257. const mpInstance = vm.$scope;
  1258. /* eslint-disable no-undef */
  1259. const minorVersion = parseInt(tt.getSystemInfoSync().SDKVersion.split('.')[1]);
  1260. if (minorVersion > 16) {
  1261. Object.defineProperty(vm, '$refs', {
  1262. get () {
  1263. const $refs = {};
  1264. const components = mpInstance.selectAllComponents('.vue-ref');
  1265. components.forEach(component => {
  1266. const ref = component.dataset.ref;
  1267. $refs[ref] = component.$vm || component;
  1268. });
  1269. const forComponents = mpInstance.selectAllComponents('.vue-ref-in-for');
  1270. forComponents.forEach(component => {
  1271. const ref = component.dataset.ref;
  1272. if (!$refs[ref]) {
  1273. $refs[ref] = [];
  1274. }
  1275. $refs[ref].push(component.$vm || component);
  1276. });
  1277. return $refs
  1278. }
  1279. });
  1280. } else {
  1281. mpInstance.selectAllComponents('.vue-ref', (components) => {
  1282. components.forEach(component => {
  1283. const ref = component.dataset.ref;
  1284. vm.$refs[ref] = component.$vm || component;
  1285. });
  1286. });
  1287. mpInstance.selectAllComponents('.vue-ref-in-for', (forComponents) => {
  1288. forComponents.forEach(component => {
  1289. const ref = component.dataset.ref;
  1290. if (!vm.$refs[ref]) {
  1291. vm.$refs[ref] = [];
  1292. }
  1293. vm.$refs[ref].push(component.$vm || component);
  1294. });
  1295. });
  1296. }
  1297. }
  1298. const instances = Object.create(null);
  1299. function initRelation ({
  1300. vuePid,
  1301. mpInstance
  1302. }) {
  1303. // 头条 triggerEvent 后,接收事件时机特别晚,已经到了 ready 之后
  1304. const nodeId = (mpInstance.__nodeId__ || mpInstance.__nodeid__) + '';
  1305. const webviewId = mpInstance.__webviewId__ + '';
  1306. instances[webviewId + '_' + nodeId] = mpInstance.$vm;
  1307. this.triggerEvent('__l', {
  1308. vuePid,
  1309. nodeId,
  1310. webviewId
  1311. });
  1312. }
  1313. function handleLink$1 ({
  1314. detail: {
  1315. vuePid,
  1316. nodeId,
  1317. webviewId
  1318. }
  1319. }) {
  1320. const vm = instances[webviewId + '_' + nodeId];
  1321. if (!vm) {
  1322. return
  1323. }
  1324. let parentVm;
  1325. if (vuePid) {
  1326. parentVm = findVmByVueId(this.$vm, vuePid);
  1327. }
  1328. if (!parentVm) {
  1329. parentVm = this.$vm;
  1330. }
  1331. vm.$parent = parentVm;
  1332. vm.$root = parentVm.$root;
  1333. parentVm.$children.push(vm);
  1334. vm.__call_hook('created');
  1335. vm.__call_hook('beforeMount');
  1336. vm._isMounted = true;
  1337. vm.__call_hook('mounted');
  1338. vm.__call_hook('onReady');
  1339. }
  1340. function parseApp (vm) {
  1341. Vue.prototype._$fallback = true; // 降级(调整原 vue 的部分生命周期,如 created,beforeMount,inject,provide)
  1342. Vue.mixin({
  1343. created () { // 处理 injections,头条 triggerEvent 是异步,且触发时机很慢,故延迟 relation 设置
  1344. if (this.mpType !== 'app') {
  1345. if (
  1346. this.mpType === 'page' &&
  1347. !this.$scope.route &&
  1348. this.$scope.__route__
  1349. ) {
  1350. this.$scope.route = this.$scope.__route__;
  1351. }
  1352. initRefs(this);
  1353. this.__init_injections(this);
  1354. this.__init_provide(this);
  1355. }
  1356. }
  1357. });
  1358. return parseBaseApp(vm, {
  1359. mocks,
  1360. initRefs: function () {} // attached 时,可能查询不到
  1361. })
  1362. }
  1363. function createApp (vm) {
  1364. App(parseApp(vm));
  1365. return vm
  1366. }
  1367. function parseBaseComponent (vueComponentOptions, {
  1368. isPage,
  1369. initRelation
  1370. } = {}) {
  1371. const [VueComponent, vueOptions] = initVueComponent(Vue, vueComponentOptions);
  1372. const options = {
  1373. multipleSlots: true,
  1374. addGlobalClass: true,
  1375. ...(vueOptions.options || {})
  1376. };
  1377. const componentOptions = {
  1378. options,
  1379. data: initData(vueOptions, Vue.prototype),
  1380. behaviors: initBehaviors(vueOptions, initBehavior),
  1381. properties: initProperties(vueOptions.props, false, vueOptions.__file),
  1382. lifetimes: {
  1383. attached () {
  1384. const properties = this.properties;
  1385. const options = {
  1386. mpType: isPage.call(this) ? 'page' : 'component',
  1387. mpInstance: this,
  1388. propsData: properties
  1389. };
  1390. initVueIds(properties.vueId, this);
  1391. // 处理父子关系
  1392. initRelation.call(this, {
  1393. vuePid: this._$vuePid,
  1394. vueOptions: options
  1395. });
  1396. // 初始化 vue 实例
  1397. this.$vm = new VueComponent(options);
  1398. // 处理$slots,$scopedSlots(暂不支持动态变化$slots)
  1399. initSlots(this.$vm, properties.vueSlots);
  1400. // 触发首次 setData
  1401. this.$vm.$mount();
  1402. },
  1403. ready () {
  1404. // 当组件 props 默认值为 true,初始化时传入 false 会导致 created,ready 触发, 但 attached 不触发
  1405. // https://developers.weixin.qq.com/community/develop/doc/00066ae2844cc0f8eb883e2a557800
  1406. if (this.$vm) {
  1407. this.$vm._isMounted = true;
  1408. this.$vm.__call_hook('mounted');
  1409. this.$vm.__call_hook('onReady');
  1410. }
  1411. },
  1412. detached () {
  1413. this.$vm && this.$vm.$destroy();
  1414. }
  1415. },
  1416. pageLifetimes: {
  1417. show (args) {
  1418. this.$vm && this.$vm.__call_hook('onPageShow', args);
  1419. },
  1420. hide () {
  1421. this.$vm && this.$vm.__call_hook('onPageHide');
  1422. },
  1423. resize (size) {
  1424. this.$vm && this.$vm.__call_hook('onPageResize', size);
  1425. }
  1426. },
  1427. methods: {
  1428. __l: handleLink,
  1429. __e: handleEvent
  1430. }
  1431. };
  1432. // externalClasses
  1433. if (vueOptions.externalClasses) {
  1434. componentOptions.externalClasses = vueOptions.externalClasses;
  1435. }
  1436. if (Array.isArray(vueOptions.wxsCallMethods)) {
  1437. vueOptions.wxsCallMethods.forEach(callMethod => {
  1438. componentOptions.methods[callMethod] = function (args) {
  1439. return this.$vm[callMethod](args)
  1440. };
  1441. });
  1442. }
  1443. if (isPage) {
  1444. return componentOptions
  1445. }
  1446. return [componentOptions, VueComponent]
  1447. }
  1448. function parseComponent (vueOptions) {
  1449. const [componentOptions, VueComponent] = parseBaseComponent(vueOptions);
  1450. componentOptions.lifetimes.attached = function attached () {
  1451. const properties = this.properties;
  1452. const options = {
  1453. mpType: isPage.call(this) ? 'page' : 'component',
  1454. mpInstance: this,
  1455. propsData: properties
  1456. };
  1457. initVueIds(properties.vueId, this);
  1458. // 初始化 vue 实例
  1459. this.$vm = new VueComponent(options);
  1460. // 处理$slots,$scopedSlots(暂不支持动态变化$slots)
  1461. initSlots(this.$vm, properties.vueSlots);
  1462. // 处理父子关系
  1463. initRelation.call(this, {
  1464. vuePid: this._$vuePid,
  1465. mpInstance: this
  1466. });
  1467. // 触发首次 setData
  1468. this.$vm.$mount();
  1469. };
  1470. // ready 比 handleLink 还早,初始化逻辑放到 handleLink 中
  1471. delete componentOptions.lifetimes.ready;
  1472. componentOptions.methods.__l = handleLink$1;
  1473. return componentOptions
  1474. }
  1475. const hooks$1 = [
  1476. 'onShow',
  1477. 'onHide',
  1478. 'onUnload'
  1479. ];
  1480. hooks$1.push(...PAGE_EVENT_HOOKS);
  1481. function parseBasePage (vuePageOptions, {
  1482. isPage,
  1483. initRelation
  1484. }) {
  1485. const pageOptions = parseComponent(vuePageOptions);
  1486. initHooks(pageOptions.methods, hooks$1, vuePageOptions);
  1487. pageOptions.methods.onLoad = function (args) {
  1488. this.$vm.$mp.query = args; // 兼容 mpvue
  1489. this.$vm.__call_hook('onLoad', args);
  1490. };
  1491. return pageOptions
  1492. }
  1493. function parsePage (vuePageOptions) {
  1494. const pageOptions = parseBasePage(vuePageOptions, {
  1495. isPage,
  1496. initRelation
  1497. });
  1498. // 页面需要在 ready 中触发,其他组件是在 handleLink 中触发
  1499. pageOptions.lifetimes.ready = function ready () {
  1500. if (this.$vm && this.$vm.mpType === 'page') {
  1501. this.$vm.__call_hook('created');
  1502. this.$vm.__call_hook('beforeMount');
  1503. this.$vm._isMounted = true;
  1504. this.$vm.__call_hook('mounted');
  1505. this.$vm.__call_hook('onReady');
  1506. } else {
  1507. this.is && console.warn(this.is + ' is not ready');
  1508. }
  1509. };
  1510. pageOptions.lifetimes.detached = function detached () {
  1511. this.$vm && this.$vm.$destroy();
  1512. // 清理
  1513. const webviewId = this.__webviewId__;
  1514. webviewId && Object.keys(instances).forEach(key => {
  1515. if (key.indexOf(webviewId + '_') === 0) {
  1516. delete instances[key];
  1517. }
  1518. });
  1519. };
  1520. return pageOptions
  1521. }
  1522. function createPage (vuePageOptions) {
  1523. {
  1524. return Component(parsePage(vuePageOptions))
  1525. }
  1526. }
  1527. function createComponent (vueOptions) {
  1528. {
  1529. return Component(parseComponent(vueOptions))
  1530. }
  1531. }
  1532. todos.forEach(todoApi => {
  1533. protocols[todoApi] = false;
  1534. });
  1535. canIUses.forEach(canIUseApi => {
  1536. const apiName = protocols[canIUseApi] && protocols[canIUseApi].name ? protocols[canIUseApi].name
  1537. : canIUseApi;
  1538. if (!tt.canIUse(apiName)) {
  1539. protocols[canIUseApi] = false;
  1540. }
  1541. });
  1542. let uni = {};
  1543. if (typeof Proxy !== 'undefined' && "mp-toutiao" !== 'app-plus') {
  1544. uni = new Proxy({}, {
  1545. get (target, name) {
  1546. if (target[name]) {
  1547. return target[name]
  1548. }
  1549. if (baseApi[name]) {
  1550. return baseApi[name]
  1551. }
  1552. if (api[name]) {
  1553. return promisify(name, api[name])
  1554. }
  1555. {
  1556. if (extraApi[name]) {
  1557. return promisify(name, extraApi[name])
  1558. }
  1559. if (todoApis[name]) {
  1560. return promisify(name, todoApis[name])
  1561. }
  1562. }
  1563. if (eventApi[name]) {
  1564. return eventApi[name]
  1565. }
  1566. if (!hasOwn(tt, name) && !hasOwn(protocols, name)) {
  1567. return
  1568. }
  1569. return promisify(name, wrapper(name, tt[name]))
  1570. },
  1571. set (target, name, value) {
  1572. target[name] = value;
  1573. return true
  1574. }
  1575. });
  1576. } else {
  1577. Object.keys(baseApi).forEach(name => {
  1578. uni[name] = baseApi[name];
  1579. });
  1580. {
  1581. Object.keys(todoApis).forEach(name => {
  1582. uni[name] = promisify(name, todoApis[name]);
  1583. });
  1584. Object.keys(extraApi).forEach(name => {
  1585. uni[name] = promisify(name, todoApis[name]);
  1586. });
  1587. }
  1588. Object.keys(eventApi).forEach(name => {
  1589. uni[name] = eventApi[name];
  1590. });
  1591. Object.keys(api).forEach(name => {
  1592. uni[name] = promisify(name, api[name]);
  1593. });
  1594. Object.keys(tt).forEach(name => {
  1595. if (hasOwn(tt, name) || hasOwn(protocols, name)) {
  1596. uni[name] = promisify(name, wrapper(name, tt[name]));
  1597. }
  1598. });
  1599. }
  1600. tt.createApp = createApp;
  1601. tt.createPage = createPage;
  1602. tt.createComponent = createComponent;
  1603. var uni$1 = uni;
  1604. export default uni$1;
  1605. export { createApp, createComponent, createPage };