以下是一个示例的 Vue ElementUI 封装组件,根据 config.js 动态展示 input、select 或 switch,当用户选择 select 值或某个 input 值变化时满足特定条件,动态变化 config.js 的内容:

<template>
  <div>
    <el-form :model="form" label-width="120px">
      <el-form-item v-for="(field, index) in config" :key="index" :label="field.label">
        <template v-if="field.type === 'input'">
          <el-input v-model="form[field.name]" @input="handleChange(field)" />
        </template>
        <template v-else-if="field.type === 'select'">
          <el-select v-model="form[field.name]" @change="handleChange(field)">
            <el-option v-for="(option, optionIndex) in field.options" :key="optionIndex" :label="option.label" :value="option.value" />
          </el-select>
        </template>
        <template v-else-if="field.type === 'switch'">
          <el-switch v-model="form[field.name]" @change="handleChange(field)" />
        </template>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import config from './config.js';

export default {
  data() {
    return {
      config: config,
      form: {}
    };
  },
  methods: {
    handleChange(field) {
      // 根据特定条件动态变化 config.js 的内容
      if (field.type === 'select') {
        // 当选择 select 值时满足特定条件
        if (this.form[field.name] === 'some value') {
          // 修改 config.js 的内容
          this.config = [
            ...this.config.slice(0, this.config.indexOf(field) + 1),
            { type: 'input', name: 'newInput', label: 'New Input', value: '' },
            ...this.config.slice(this.config.indexOf(field) + 1)
          ];
        } else {
          // 恢复原始的 config.js 内容
          this.config = config;
        }
      } else if (field.type === 'input') {
        // 当某个 input 值变化时满足特定条件
        if (this.form[field.name] === 'some value') {
          // 修改 config.js 的内容
          this.config = [
            ...this.config.slice(0, this.config.indexOf(field) + 1),
            { type: 'select', name: 'newSelect', label: 'New Select', value: '', options: [{ label: 'Option 1', value: 'option1' }, { label: 'Option 2', value: 'option2' }] },
            ...this.config.slice(this.config.indexOf(field) + 1)
          ];
        } else {
          // 恢复原始的 config.js 内容
          this.config = config;
        }
      }
    }
  }
};
</script>

在上述示例中,我们在组件的 data 中定义了 config 对象数组和 form 对象。config 对象数组用于存储动态展示的字段配置,form 对象用于存储表单字段的值。

通过遍历 config 数组,根据 fieldtype 属性来渲染对应的表单字段,在用户修改表单字段的值时调用 handleChange 方法。在 handleChange 方法中,根据特定条件动态变化 config 数组,从而实现动态展示和变化。

请根据实际需求修改以上代码,并将其放在一个 Vue 组件中以供使用


原文地址: https://www.cveoy.top/t/topic/hXO3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录