d-render
Version:
数据渲染库 - form、table、search-form
81 lines (78 loc) • 3.06 kB
JavaScript
import { ref, toRef, computed, watch } from 'vue';
import { getFieldValue } from '@d-render/shared';
import { getChangeIndex, getValuesByKeys } from '../util';
const useFieldChange = (props, securityConfig, dependOnWatchCb) => {
const changeCount = ref(0);
const dependOnValues = ref({});
const outDependOnValues = ref({});
const tableDependOnValues = toRef(props, "tableDependOnValues");
const parentDependOnValues = toRef(props, "parentDependOnValues");
const model = toRef(props, "model");
const dependOn = computed(() => securityConfig.value.dependOn || []);
const outDependOn = computed(() => securityConfig.value.outDependOn || []);
const filterSelf = (dependOn2) => {
return dependOn2.filter((key) => {
if (typeof key === "object")
key = key.key;
return key !== props.fieldKey;
});
};
const depend = props.inTable || props.inParent ? filterSelf(dependOn.value).concat(outDependOn.value) : filterSelf(dependOn.value);
const generateWatchValue = () => {
let result = watchValue(model, filterSelf(dependOn.value));
if (props.inTable) {
result = result.concat(watchValue(tableDependOnValues, outDependOn.value));
}
if (props.inParent) {
result = result.concat(watchValue(parentDependOnValues, outDependOn.value));
}
return result;
};
const watchValue = (target, dependOn2) => dependOn2.map((key) => {
if (typeof key === "object")
key = key.key;
return () => getFieldValue(target.value, key);
});
const getChange = (values, oldValues, depend2) => {
const changeIndex = getChangeIndex(values, oldValues);
const changeValue = changeIndex.map((index) => values[index]);
const changeOldValues = changeIndex.map((index) => oldValues[index]);
const changeKeys = changeIndex.map((index) => depend2[index]);
return { changeValue, changeOldValues, changeKeys };
};
const collectDependInfo = () => {
const values = getValuesByKeys(model.value, dependOn.value);
let outValues = {};
if (props.inTable) {
outValues = getValuesByKeys(tableDependOnValues.value, outDependOn.value);
}
if (props.inParent) {
outValues = getValuesByKeys(parentDependOnValues.value, outDependOn.value);
}
dependOnValues.value = values;
outDependOnValues.value = outValues;
};
if (depend.length > 0) {
let firstChange;
watch(() => props.model, () => {
changeCount.value++;
firstChange = true;
}, { deep: false, immediate: true });
watch(generateWatchValue(), (values, oldValues) => {
const change = getChange(values, oldValues, depend);
collectDependInfo();
dependOnWatchCb(change, {
executeChangeValueEffect: securityConfig.value.immediateChangeValue || !firstChange,
values: dependOnValues.value,
outValues: outDependOnValues.value
});
firstChange = false;
}, { deep: true, immediate: true, flush: "post" });
}
return {
changeCount,
dependOnValues,
outDependOnValues
};
};
export { useFieldChange };