使用 vue/vuetify 建模自定义属性 CRUD

Model custom attributes CRUD with vue/vuetify

后端业务对象包含自定义属性数据结构,允许客户端添加 key/value 对以在数据库中持久化。例如:Map<String, String> customAttributes;

UI 示例:(能够添加额外的行)

在 vue 的数据函数中,我有一个用于此数据的占位符:

data() {
    return {
      customAttributes: {},
      ...
    }

但我想不出一种方法将 UI 输入绑定到 customAttributes 对象,以便添加新行(属性)为其添加相应的键和值。

是否有其他处理方法?

我不会为此使用 Map,因为 Vue 将很难跟踪对象键,如果它们可以很容易地更改的话。似乎更适合使用 Array<{ key: string, value: string }>

如果你确实需要 map 版本,你可以很容易地从数组

中计算出来

const model = { key: "", value: "" }

new Vue({
  el: "#app",
  data: () => ({
    attributes: [{
      key: "GRADLE_HOME",
      value: "/usr/local/gradle"
    }, {
      key: "JAVA_HOME",
      value: "/usr/lib/jvm/whatever"
    }]
  }),
  computed: {
    attributeMap: ({ attributes }) =>
      Object.fromEntries(attributes.map(({ key, value }) => [ key, value ]))
  },
  methods: {
    add () {
      this.attributes.push({...model})
    },
    del (index) {
      this.attributes.splice(index, 1)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <table border="1">
    <thead><tr><th>Name</th><th>Value</th></tr></thead>
    <tbody>
      <tr v-for="(attr, index) in attributes" :key="index">
        <td><input v-model="attr.key"/></td>
        <td>
          <input v-model="attr.value" />
          <button @click="del(index)">&times;</button>
        </td>
      </tr>
    </tbody>
    <tfoot>
      <tr><td colspan="2"><button @click="add">Add Attribute</button></td></tr>
    </tfoot>
  </table>
  <pre>attributeMap = {{ attributeMap }}</pre>
</div>