首页 > 解决方案 > 如何在 Vue 中从 JSON 构建动态 HTML 控件?

问题描述

美好的一天社区。

我需要您的帮助才能在 VUE 中从 JSON 动态构建 HTML 控件。

目前我已经完成了一个练习,我有一个 html 模板,它根据 JSON 中设置的参数呈现输入控件列表。但是我想构建更多控件,而不仅仅是输入控件。

export default {
  name: 'app',
  data () {
    return {
      msg: 'Hola Mundo',
      fields: [
        {
          "name": "fechaRegistro",
          "label": "Fecha de Registro",
          "type": "date",
          "placeholder": 'Ingresa Fecha'
        },
        {
          "name": "nombreDeUsuario",
          "label": "Nombre de Usuario",
          "type": "text",
          "placeholder": "Ingresa Usuario"
        },
        {
          "name": "passwordUsuario",
          "label": "Password",
          "type": "password",
          "placeholder": "Contraseña"
        },
        {
          "name": "adjuntarArchivo",
          "label": "Adjuntar",
          "type": "file"
        },
        {
          "name": "activo",
          "label": "Activo",
          "type": "checkbox"
        },
        {
          "name": "roles",
          "label": "Roles",
          "type": "multiSelect",
          "sortedByKey": false,
          "options": [{
              "name": "admin",
              "label": "Admin"
            },
            {
              "name": "user",
              "label": "User"
            },
            {
              "name": "guest",
              "label": "Invitado"
            }
          ]
        }
      ]
    }
  }
}
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
<template>
  <div id="app">
    <h1>{{msg}}</h1>
    <form>
      <ul id="controles">
        <li v-for="field in fields" :key="field">
          <label :for="field.name">{{field.label}}</label>
          <input :id="field.name" :type="field.type" :placeholder="field.placeholder">
        </li>
      </ul>
    </form>
  </div>
</template>

我的目标是在 Json 中接收我应该构建的控件类型及其参数。比如json里来了一个select类型的控件,我必须建一个select,如果来了一个textarea类型的控件,我就必须建一个textarea等等。

请留下您的解决方案,谢谢。

标签: javascripthtmlvue.jstemplatescomponents

解决方案


您需要提前知道预期的字段类型。您可以创建这样的方法hasInputTag

methods: {
  hasInputTag(type) {
    return ['text', 'password', 'file', 'date'].includes(type);
  }
}

然后检查循环field.type内部v-for并渲染适当的元素,例如:

<li v-for="field in fields" :key="field">
  <label :for="field.name">
    {{ field.label }}
  </label>
  <input
    v-if="hasInputTag(field.type)"
    :name="field.name"
    :type="field.type"
  >
  <select
    v-else-if="field.type === 'select'"
    :name="field.name"
  >
    <option v-for="opt in field.options">
      // etc.
    </option>
  </select>
  <textarea
    v-else-if="field.type === 'textarea'"
    :name="field.name"
  >
</li>

更新 1:

如果您想使用单独的组件,您可以在模板中执行以下操作:

<component
  :is="getComponentName(field.type)"
  v-bind="field"
/>

您的getComponentName方法可能如下所示(其中每个组件都有一个名称,例如Custom_input,Custom_checkbox等,并且您已将它们导入父级):

getComponentName(type) {
  if (['text', 'password', 'file', 'date'].includes(type)) return 'Custom_input';
  return `Custom_${type}`;
}

更新 2:

为了存储每个组件的值,我会fieldValues在父级中创建一个对象并像这样初始化它:

fieldValues: this.fields.reduce((res, field) => {
  res[field.name] = null;
  return res;
}, {})

然后v-model="fieldValues[field.name]"在你的循环中使用。


推荐阅读