首页 > 解决方案 > 从嵌套对象生成 vue 组件

问题描述

有没有什么好的方法可以使用嵌套对象生成vue组件?

我有一个看起来像这样的深层嵌套对象:

"api": {
  "v1": {
    "groups": {
       "create": true,
       "get": true,
       "item": {
          "get": true,
          "destroy": false
      }
    }
  }
}

我想生成一个表单,其中包含对象的每个值的复选框。我无法将对象的值绑定到 Vue 复选框中的 v-models

我尝试制作一个查找键列表,如 ["api.v1.groups.create", "api.v1.groups.get"] 然后使用如下函数获取条目:

getPerm (p) {
  return p.split('.').reduce(
    (xs, x) => (xs && xs[x]) ? xs[x] : null,
    this.role.permissions)
}

但是,这不起作用,因为它给了我布尔值而不是参考值。

标签: javascriptvue.jsdictionary

解决方案


查看我的: Code sandbox to flatten dict and create a list from an nested entry

(我从一个基本的 Vue 模板中分出了它,所以它仍然有一些对“图表”的引用)

v-for扁平化字典后,您可以像往常一样使用它们生成 vue 组件!

如果您想在现场查看,以下是我用来展平字典的处理:

// Define out nested object
var nested = {
  "api": {
    "v1": {
      "groups": {
        "create": true,
        "get": true,
        "item": {
          "get": true,
          "destroy": false
        }
      }
    }
  }
}

// function for checking if we are at the bottom of the Object
const isObj = o => o?.constructor === Object;

// I had to use a class to store the output in the different recursive scopes
class NestedProcessor {
  // Constructur starts the function and returns the dictionary as flat
  constructor(leveled_dict) {
    this.output = {}
    this.process_dict_recursive(leveled_dict)
    return this.ouput
  }
  process_dict_recursive(leveled_dict, keyList = [], depth = 0) {
    if (isObj(leveled_dict)) { // check if we have hit the bottom
      keyList.push('')
      depth++ 
      for (let key in leveled_dict) { 
        keyList[depth - 1] = key
        this.process_dict_recursive(leveled_dict[key], keyList, depth) // call the function recursively at our new depth
      }
    }
    else {
      // Create our lookup keys
      let path = ''
      keyList.forEach((v) => {
        path += v
        path += '.'
      })
      path = path.slice(0, -1) // Remove the last '.'
      this.output[path] = leveled_dict
    }
  }
}

console.log(new NestedProcessor(nested))
//{
//  "output": {
//    "api.v1.groups.create": true,
//    "api.v1.groups.get": true,
//    "api.v1.groups.item.get": true,
//    "api.v1.groups.item.destroy": false
//  }
//}

笔记:

  • 我使用了一个类,因为我不知道如何在递归中处理变量范围
  • 我需要一种方法来检查我们是否处于底部,所以从 SO 中获取了一个函数来检查它。

推荐阅读