前言
- Vue3
- setup语法糖
- v-for按需遍历
- 记录两次数据的diff算法,用来判断是否发起请求
- 按需提取源数据内容遍历
1.template
<div>
<h1>学习遍历多选框按钮,按需求v-for</h1>
<a-form ref="sysForm" :model="info" :label-col="{ span: 8 }" :wrapper-col="{ span: 8 }">
<a-form-item :label="服务" :wrapper-col="{ span: 16 }">
<a-checkbox
v-for="(s, index) in svctbl"
:key="index"
v-model:checked="info[s.dataIndex]"
>{
{
s.label }}</a-checkbox
>
</a-form-item>
<a-button type="primary" @click="onclick('apply')">Apply</a-button>
<a-button type="danger" @click="onclick('reset')">Reset</a-button>
</a-form>
</div>
2.Setup
<script setup lang="ts">
import {
getCurrentInstance, computed, ref, onMounted } from 'vue';
import Child from './Child.vue';
import {
useI18n } from '/@/hooks/web/useI18n';
const {
t } = useI18n();
const currentInstance = getCurrentInstance();
const child = ref(null);
const emitsData = ref(null);
const exposeData2 = ref(null);
const defSvctbl = [
{
label: 'telnet', dataIndex: 'telnet' },
{
label: 'ssh', dataIndex: 'ssh' },
{
label: 'http', dataIndex: 'http' },
{
label: 'https', dataIndex: 'https' },
];
const svctbl = computed(() => defSvctbl);
function shallowDiff(newObj, orgObj) {
if (!newObj || !orgObj) return newObj;
const res = Object.keys(newObj)
.filter((k) => typeof newObj[k] !== 'object')
.filter((k) => newObj[k] !== orgObj[k])
.reduce((acc, k) => ({
...acc, [k]: newObj[k] }), {
});
return res;
}
const info = ref({
});
let orgInfo = {
};
const sysForm = ref();
function refresh() {
let data = {
telnet: false,
https: true,
ssh: false,
http: true,
};
info.value = {
...data };
orgInfo = JSON.parse(JSON.stringify({
...data }));
info.value = {
...data };
}
async function onclick(type) {
if (type === 'reset') {
sysForm.value.clearValidate();
info.value = JSON.parse(JSON.stringify(orgInfo));
return;
}
if (type === 'apply') {
try {
await sysForm.value.validateFields();
let diff = shallowDiff(info.value, orgInfo);
console.log('[config] diff %o, mgmtDiff %o', diff);
Object.keys(diff).length && console.log('修改成功');
refresh();
} catch {
}
return;
}
}
onMounted(() => {
refresh();
});
function show() {
child.value.alertMessage();
exposeData2.value = child.value.message;
console.log(child.value.message);
}
function recState(e) {
emitsData.value = e;
console.log('收到子组件child通过emits传来的数据', e);
}
</script>
3.效果
- 当修改数据后会调用diff算法判断,与初始内容有出入时按下Apply才会进行下一步操作
- 修改后发送修改接口,之后重新刷新就是修改之后的内容