1. 需求
如下表单,所有input框、select框、switch都是根据后端传过来的type数据动态生成的。
2. 实现
2.1 template:
:is=“组件实例”
v-model:value=“组件绑定的值”
:info=“父子组件传值”
2.2 引入需要动态生成的组件
// input框组件
import TaskScanTest from "../../components/task/components/TaskScanTest";
// select框组件
import TaskSelectTest from "../../components/task/components/TaskSelectTest";
// switch组件
import TaskSwitchTest from "../../components/task/components/TaskSwitchTest";
3. 父子组件传值
3.1 子组件接收值和方法
实现动态组件的渲染之后,子组件需要接收值:
defineComponent:
name: "TaskScanTest",
props: ["info", "value"],
emits: ["update:value", "execute-after-option", "focus-next-slot"],
setup(props, { emit }) {
const optionInfo = reactive<rowFormI>(props.info);
const optionValue = ref(props.value);
return { optionInfo, optionValue };
}
template:
<el-input v-model="optionValue" style="width: 250px" ></el-input>
3.2 子组件监听值的变化
watch(
() => props.value,
() => {
optionValue.value = props.value;
}
);
watch(
() => optionValue.value,
(newValue: string, oldValue: string) => {
// 单个数据更新
emit("update:value", newValue);
}
);