Browse Source

fix(devtools): fix no getters displayed on root module + better getters inspector (#1986)

Guillaume Chau 4 years ago
parent
commit
bc20295331
1 changed files with 40 additions and 3 deletions
  1. 40 3
      src/plugins/devtool.js

+ 40 - 3
src/plugins/devtool.js

@@ -59,7 +59,7 @@ export function addDevtools (app, store) {
           makeLocalGetters(store, modulePath)
           payload.state = formatStoreForInspectorState(
             getStoreModule(store._modules, modulePath),
-            store._makeLocalGettersCache,
+            modulePath === 'root' ? store.getters : store._makeLocalGettersCache,
             modulePath
           )
         }
@@ -228,16 +228,45 @@ function formatStoreForInspectorState (module, getters, path) {
   }
 
   if (gettersKeys.length) {
-    storeState.getters = gettersKeys.map((key) => ({
+    const tree = transformPathsToObjectTree(getters)
+    storeState.getters = Object.keys(tree).map((key) => ({
       key: key.endsWith('/') ? extractNameFromPath(key) : key,
       editable: false,
-      value: getters[key]
+      value: canThrow(() => tree[key])
     }))
   }
 
   return storeState
 }
 
+function transformPathsToObjectTree (getters) {
+  const result = {}
+  Object.keys(getters).forEach(key => {
+    const path = key.split('/')
+    if (path.length > 1) {
+      let target = result
+      const leafKey = path.pop()
+      for (const p of path) {
+        if (!target[p]) {
+          target[p] = {
+            _custom: {
+              value: {},
+              display: p,
+              tooltip: 'Module',
+              abstract: true
+            }
+          }
+        }
+        target = target[p]._custom.value
+      }
+      target[leafKey] = canThrow(() => getters[key])
+    } else {
+      result[key] = canThrow(() => getters[key])
+    }
+  })
+  return result
+}
+
 function getStoreModule (moduleMap, path) {
   const names = path.split('/').filter((n) => n)
   return names.reduce(
@@ -251,3 +280,11 @@ function getStoreModule (moduleMap, path) {
     path === 'root' ? moduleMap : moduleMap.root._children
   )
 }
+
+function canThrow (cb) {
+  try {
+    return cb()
+  } catch (e) {
+    return e
+  }
+}