index-dev.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. class Utils {
  2. getHashRoute() {
  3. let hashDetail = window.location.hash.split('?');
  4. let hashName = hashDetail[0].split('#')[1];
  5. let params = hashDetail[1] ? hashDetail[1].split('&') : [];
  6. let query = {};
  7. params.map((item) => {
  8. let temp = item.split('=');
  9. query[temp[0]] = temp[1];
  10. });
  11. return {
  12. path: hashName,
  13. query: query
  14. };
  15. }
  16. getHistoryRoute() {
  17. let path = (window.history.state && window.history.state.path) || '';
  18. let queryStr = window.location.hash.split('?')[1];
  19. let params = queryStr ? queryStr.split('&') : [];
  20. let query = {};
  21. params.map((item) => {
  22. let temp = item.split('=');
  23. query[temp[0]] = temp[1];
  24. });
  25. return {
  26. path: path,
  27. query: query
  28. };
  29. }
  30. /**
  31. * 发送Get请求
  32. *
  33. * @param {!string} url 请求地址
  34. * @param {?function} next 回调函数
  35. */
  36. static ajaxGet(url, next) {
  37. let xhr = new XMLHttpRequest();
  38. if (url.includes('?')) {
  39. // 在URL有其他参数时,添加一个date参数加入当前时间以避免缓存
  40. xhr.open('GET', `${url}&date=${new Date().getTime()}`, true);
  41. } else {
  42. // 添加一个date参数加入当前时间以避免缓存
  43. xhr.open('GET', `${url}&date=${new Date().getTime()}`, true);
  44. }
  45. xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  46. // 更改XMLHttpRequest对象withCredentials属性以支持跨域Cookies
  47. xhr.withCredentials = true;
  48. xhr.responseType = 'json';
  49. xhr.onload = function (res) {
  50. // 获取请求接口返回值
  51. let response = res.target.response;
  52. next && next(response);
  53. };
  54. xhr.send();
  55. }
  56. /**
  57. * 发送Post请求
  58. *
  59. * @param {!string} url 请求地址
  60. * @param {?string} data post请求参数
  61. * @param {?function} next 回调函数
  62. */
  63. static ajaxPost(url, data, next) {
  64. let xhr = new XMLHttpRequest();
  65. if (url.includes('?')) {
  66. // 在URL有其他参数时,添加一个date参数加入当前时间以避免缓存
  67. xhr.open("POST", `${url}&${new Date().getTime()}`, true);
  68. } else {
  69. // 添加一个date参数加入当前时间以避免缓存
  70. xhr.open("POST", `${url}?${new Date().getTime()}`, true);
  71. }
  72. xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  73. // 更改XMLHttpRequest对象withCredentials属性以支持跨域Cookies
  74. xhr.withCredentials = true;
  75. xhr.responseType = 'json';
  76. xhr.onload = function (res) {
  77. // 获取请求接口返回值
  78. let response = res.target.response;
  79. next && next(response);
  80. };
  81. xhr.send(data);
  82. }
  83. /**
  84. * 事件监听处理类
  85. *
  86. * @param {string} eventName 表示监听事件类型的字符串
  87. * @param {object} [{ onElement, withCallback, useCapture = false }={}] 监听对象 回调函数 useCapture
  88. * @param {function} thisArg
  89. * @returns function
  90. */
  91. static handleEvent(eventName, {
  92. onElement,
  93. withCallback,
  94. useCapture = false
  95. } = {}, thisArg) {
  96. const element = onElement || document.documentElement
  97. function handler(event) {
  98. if (typeof withCallback === 'function') {
  99. withCallback.call(thisArg, event)
  100. }
  101. }
  102. handler.destroy = function () {
  103. return element.removeEventListener(eventName, handler, useCapture)
  104. }
  105. element.addEventListener(eventName, handler, useCapture)
  106. return handler
  107. }
  108. }
  109. /**
  110. * declare route: { path: '/xx', fileName: 'xxx', initFunc(){}}
  111. *
  112. *
  113. * @class SPARouter
  114. */
  115. class SPARouter {
  116. constructor(el, routers, mode) {
  117. this.el = el;
  118. this.mode = mode || 'hash';
  119. this.utils = new Utils();
  120. this.currentRoute = {};
  121. this.beforeFunc = null;
  122. this.afterFunc = null;
  123. this.initRouters(routers);
  124. this.init();
  125. }
  126. init() {
  127. window.SPA_RESOLVE_INIT = null;
  128. this.initEvent();
  129. }
  130. initRouters(routers) {
  131. this.routers = routers.map((item) => {
  132. item.$router = this;
  133. return item;
  134. });
  135. }
  136. initEvent() {
  137. window.addEventListener('load', () => {
  138. console.log('load')
  139. this.routeUpdate();
  140. });
  141. if (this.mode === 'history') {
  142. window.addEventListener('popstate', (e) => {
  143. console.log('popstate')
  144. this.routeUpdate();
  145. });
  146. // 禁用所有a 链接默认跳转事件
  147. let self = this;
  148. document.addEventListener('click', function (e) {
  149. let target = e.target || e.srcElement;
  150. if (target.tagName === 'A') {
  151. e.preventDefault();
  152. let href = target.getAttribute('href');
  153. let path = href.split('?')[0];
  154. window.history.pushState({
  155. path: path
  156. }, null, href);
  157. self.routeUpdate();
  158. }
  159. })
  160. } else {
  161. window.addEventListener('hashchange', () => {
  162. console.log('hashchange')
  163. this.routeUpdate();
  164. });
  165. }
  166. }
  167. loadComponent() {
  168. let self = this;
  169. if (typeof (self.currentRoute.fn) === 'function') {
  170. self.currentRoute.fn(self.el, self.currentRoute);
  171. } else {
  172. if (this.currentRoute.fileName) {
  173. let _body = document.getElementsByTagName('body')[0];
  174. let scriptEle = document.createElement('script');
  175. scriptEle.src = self.currentRoute.fileName;
  176. scriptEle.async = true;
  177. scriptEle.type = 'text/javascript';
  178. window.SPA_ROUTE_INIT = null;
  179. scriptEle.onload = () => {
  180. self.afterFunc && self.afterFunc(self.currentRoute);
  181. self.currentRoute.fn = window.SPA_RESOLVE_INIT;
  182. self.currentRoute.fn(self.el, self.currentRoute);
  183. }
  184. _body.appendChild(scriptEle);
  185. } else {
  186. if (self.currentRoute.initFunc) {
  187. self.currentRoute.initFunc(self.el, self.currentRoute);
  188. self.afterFunc && self.afterFunc(self.currentRoute);
  189. } else {
  190. console.trace('该路由定义出错,fileName 和 initFunc 必须定义一个')
  191. }
  192. }
  193. }
  194. }
  195. refresh(currentHash) {
  196. let self = this;
  197. if (self.beforeFunc) {
  198. self.beforeFunc({
  199. path: self.currentRoute.path,
  200. query: self.currentRoute.query
  201. }, () => {
  202. self.loadComponent();
  203. })
  204. } else {
  205. self.loadComponent();
  206. }
  207. }
  208. routeUpdate() {
  209. let getLocation = this.mode === 'history' ? this.utils.getHistoryRoute : this.utils.getHashRoute;
  210. let currentLocation = getLocation();
  211. this.currentRoute.query = currentLocation['query']
  212. this.routers.map((item) => {
  213. if (item.path === currentLocation.path) {
  214. this.currentRoute = item;
  215. this.refresh();
  216. }
  217. });
  218. if (!this.currentRoute.path) {
  219. if (this.mode === 'history') {
  220. window.history.pushState({
  221. path: '/index'
  222. }, null, '/index');
  223. this.routeUpdate();
  224. } else {
  225. location.hash = '/index';
  226. }
  227. }
  228. }
  229. beforeEach(callback) {
  230. if (Object.prototype.toString.call(callback) === '[object Function]') {
  231. this.beforeFunc = callback;
  232. } else {
  233. console.trace('路由切换前钩子函数不正确')
  234. }
  235. }
  236. afterEach(callback) {
  237. if (Object.prototype.toString.call(callback) === '[object Function]') {
  238. this.afterFunc = callback;
  239. } else {
  240. console.trace('路由切换后钩子函数不正确')
  241. }
  242. }
  243. }