Переглянути джерело

use $router magic insteand of $store.router

Shaun Li 2 роки тому
батько
коміт
33f373556c
1 змінених файлів з 29 додано та 29 видалено
  1. 29 29
      src/index.js

+ 29 - 29
src/index.js

@@ -9,35 +9,7 @@ export default function (Alpine) {
     loading: false
   })
 
-  function push (path, options = {}) {
-    if (!path.startsWith(location.origin)) {
-      if (state.mode === 'hash') {
-        path = location.origin + (state.base || '/') + '#' + path
-      } else {
-        path = location.origin + state.base + path
-      }
-    }
-    if (location.href !== path) {
-      history[options.replace ? 'replaceState' : 'pushState']({}, '', path)
-      state.href = path
-    }
-  }
-
-  function replace (path) {
-    push(path, { replace: true })
-  }
-
-  Alpine.store('router', {
-    init () {
-      Alpine.effect(() => {
-        state.query = (state.href.indexOf('?') > -1)
-          ? Object.fromEntries(new URLSearchParams(state.href.split('?').pop()).entries())
-          : {}
-      })
-
-      window.addEventListener('popstate', () => state.href = location.href)
-    },
-
+  const router = {
     get path () {
       return state.path
     },
@@ -69,8 +41,36 @@ export default function (Alpine) {
         ...query
       }).toString()
     }
+  }
+
+  Alpine.magic('router', () => router)
+
+  Alpine.effect(() => {
+    state.query = (state.href.indexOf('?') > -1)
+      ? Object.fromEntries(new URLSearchParams(state.href.split('?').pop()).entries())
+      : {}
   })
 
+  window.addEventListener('popstate', () => state.href = location.href)
+
+  function push (path, options = {}) {
+    if (!path.startsWith(location.origin)) {
+      if (state.mode === 'hash') {
+        path = location.origin + (state.base || '/') + '#' + path
+      } else {
+        path = location.origin + state.base + path
+      }
+    }
+    if (location.href !== path) {
+      history[options.replace ? 'replaceState' : 'pushState']({}, '', path)
+      state.href = path
+    }
+  }
+
+  function replace (path) {
+    push(path, { replace: true })
+  }
+
   function buildPattern (path) {
     const pattern = path.split('/').map(e => {
       if (e.startsWith(':')) {