【问题标题】:Generate vue components from a nested object从嵌套对象生成 vue 组件
【发布时间】:2020-11-18 13:31:04
【问题描述】:

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

我有一个嵌套很深的对象,如下所示:

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

我想生成一个表单,其中包含对象的每个值的复选框。 我在将对象的值绑定到 Vue 复选框中的 v-model 时遇到问题

我尝试制作一个查找键列表,例如 ["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)
}

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

【问题讨论】:

  • 哇,我昨天遇到了同样的问题!我最终使用了递归,但它假定所有具有值的键都是唯一的,这里不是这种情况。
  • 真的很抱歉,我刚刚重新阅读了这篇文章,并认为我们可能有不同的问题。您正在尝试在对象内为您的 vue 组件找到引用,对吗?是否可以在将“api”输入输入到您的 vue 组件之前对其进行处理?
  • @JesseRezaKhorasanee 我实际上是在尝试这样做:每个条目的 v-model="model.api.v1.groups.create"
  • 啊,好吧,我想我现在明白了。我们不能只使用watch 将我们的输入处理成一个单独的对象并将我们的v-models 指向它吗?我目前正忙于其他事情,但我会尽快尝试一下
  • 我要试试你建议的方法,看看效果如何

标签: javascript vue.js dictionary


【解决方案1】:

查看我的: Code sandbox to flatten dict and create a list from a 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 中获取了一个函数来检查。

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 1970-01-01
    • 2022-01-21
    • 2021-12-06
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    相关资源
    最近更新 更多