vue3 自定义调控参数-简易生成器
- 此功能好像是某厂的在线视频笔试题,当时写完也没有结果。。。
- 我觉得此 demo 适用场景:自定义动态表单时需要定制字段、用户自定义信息等
封装生成器控件如下
//创建CustomControlParams.vue 文件, 内容如下
<template>
<div v-for="(item, index) in keyValArr">
<input type="text" v-model="item.prop" @input="setObj" />
<span>:</span>
<input type="text" v-model="item.value" @input="setObj" />
<button @click="() => onDelete(item.id)">删除</button>
</div>
<button @click="onAdd">新增字段</button>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
//获取随机字符串 32uuid
const getRandomStr = (length = 32) => {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const maxPos = chars.length;
let _string = "";
for (let i = 0; i < length; i++) {
_string += chars.charAt(Math.floor(Math.random() * maxPos));
}
return _string;
}
const props = defineProps({
customeKeyValue: {
type: Object,
default: {}
}
});
const emits = defineEmits(["update:customeKeyValue"]);
//对象映射成数组,方便操作
const keyValArr = ref<{
id: string;
prop: string;
value: any;
}[]>([]);
//初始转换
onMounted(() => {
keyValArr.value = Object.keys(props.customeKeyValue).map(prop => ({
id: getRandomStr(),
prop,
value: props.customeKeyValue[prop]
}));
});
//操作值变化时,同步修改
const setObj = () => {
let newCustomeKeyValue = {} as any;
keyValArr.value.map(item => {
newCustomeKeyValue[item.prop] = item.value;
});
emits("update:customeKeyValue", newCustomeKeyValue);
};
//删除
const onDelete = (prop: string) => {
keyValArr.value = keyValArr.value.filter(item => item.prop !== prop);
setObj();
};
//添加
const onAdd = () => {
keyValArr.value.push({
id: getRandomStr(),
prop: 'Custom' + Date.now(),
value: ""
});
setObj();
};
</script>
父组件使用如下:
<template>
<h2>自定义调控参数</h2>
<CustomControlParams v-model:customeKeyValue="formVal" />
<div>{{ formVal }}</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import CustomControlParams from "./CustomControlParams.vue";
const formVal = ref<any>({
MAX: 1,
MIN: 2
})
</script>
结果如图:
- 没有做相同属性 key 的校验,相同的默认会后定义覆盖之前定义。
- demo 记录而已。不喜勿喷
有疑问的同学可以私信我、对帮助到同学欢迎大家点赞、收藏评论。