refactor(AddressEdit): refactor with composition api

This commit is contained in:
chenjiahan 2020-09-24 17:19:14 +08:00
parent d2a5427976
commit 749e4ae73b

View File

@ -1,7 +1,12 @@
import { h, ref, watch, computed, nextTick, reactive } from 'vue';
// Utils // Utils
import { createNamespace, isObject } from '../utils'; import { createNamespace, isObject } from '../utils';
import { isMobile } from '../utils/validate/mobile'; import { isMobile } from '../utils/validate/mobile';
// Composition
import { useExpose } from '../composition/use-expose';
// Components // Components
import Area from '../area'; import Area from '../area';
import Cell from '../cell'; import Cell from '../cell';
@ -94,8 +99,10 @@ export default createComponent({
'change-default', 'change-default',
], ],
data() { setup(props, { emit, slots }) {
return { const areaRef = ref();
const state = reactive({
data: {}, data: {},
showAreaPopup: false, showAreaPopup: false,
detailFocused: false, detailFocused: false,
@ -106,16 +113,14 @@ export default createComponent({
postalCode: '', postalCode: '',
addressDetail: '', addressDetail: '',
}, },
}; });
},
computed: { const areaListLoaded = computed(
areaListLoaded() { () => isObject(props.areaList) && Object.keys(props.areaList).length
return isObject(this.areaList) && Object.keys(this.areaList).length; );
},
areaText() { const areaText = computed(() => {
const { country, province, city, county, areaCode } = this.data; const { country, province, city, county, areaCode } = state.data;
if (areaCode) { if (areaCode) {
const arr = [country, province, city, county]; const arr = [country, province, city, county];
if (province && province === city) { if (province && province === city) {
@ -124,103 +129,34 @@ export default createComponent({
return arr.filter((text) => text).join('/'); return arr.filter((text) => text).join('/');
} }
return ''; return '';
},
// hide bottom field when use search && detail get focused
hideBottomFields() {
const { searchResult } = this;
return searchResult && searchResult.length && this.detailFocused;
},
},
watch: {
addressInfo: {
handler(val) {
this.data = {
...defaultData,
...val,
};
this.setAreaCode(val.areaCode);
},
deep: true,
immediate: true,
},
areaList() {
this.setAreaCode(this.data.areaCode);
},
},
methods: {
onFocus(key) {
this.errorInfo[key] = '';
this.detailFocused = key === 'addressDetail';
this.$emit('focus', key);
},
onChangeDetail(val) {
this.data.addressDetail = val;
this.$emit('change-detail', val);
},
onAreaConfirm(values) {
values = values.filter((value) => !!value);
if (values.some((value) => !value.code)) {
Toast(t('areaEmpty'));
return;
}
this.showAreaPopup = false;
this.assignAreaValues();
this.$emit('change-area', values);
},
assignAreaValues() {
const { area } = this.$refs;
if (area) {
const detail = area.getArea();
detail.areaCode = detail.code;
delete detail.code;
Object.assign(this.data, detail);
}
},
onSave() {
const items = ['name', 'tel'];
if (this.showArea) {
items.push('areaCode');
}
if (this.showDetail) {
items.push('addressDetail');
}
if (this.showPostal) {
items.push('postalCode');
}
const isValid = items.every((item) => {
const msg = this.getErrorMessage(item);
if (msg) {
this.errorInfo[item] = msg;
}
return !msg;
}); });
if (isValid && !this.isSaving) { // hide bottom field when use search && detail get focused
this.$emit('save', this.data); const hideBottomFields = computed(() => {
const { searchResult } = props;
return searchResult && searchResult.length && state.detailFocused;
});
const assignAreaValues = () => {
if (areaRef.value) {
const detail = areaRef.value.getArea();
detail.areaCode = detail.code;
delete detail.code;
Object.assign(state.data, detail);
} }
}, };
getErrorMessage(key) { const onFocus = (key) => {
const value = String(this.data[key] || '').trim(); state.errorInfo[key] = '';
state.detailFocused = key === 'addressDetail';
emit('focus', key);
};
if (this.validator) { const getErrorMessage = (key) => {
const message = this.validator(key, value); const value = String(state.data[key] || '').trim();
if (props.validator) {
const message = props.validator(key, value);
if (message) { if (message) {
return message; return message;
} }
@ -230,63 +166,106 @@ export default createComponent({
case 'name': case 'name':
return value ? '' : t('nameEmpty'); return value ? '' : t('nameEmpty');
case 'tel': case 'tel':
return this.telValidator(value) ? '' : t('telInvalid'); return props.telValidator(value) ? '' : t('telInvalid');
case 'areaCode': case 'areaCode':
return value ? '' : t('areaEmpty'); return value ? '' : t('areaEmpty');
case 'addressDetail': case 'addressDetail':
return value ? '' : t('addressEmpty'); return value ? '' : t('addressEmpty');
case 'postalCode': case 'postalCode':
return value && !this.postalValidator(value) ? t('postalEmpty') : ''; return value && !props.postalValidator(value) ? t('postalEmpty') : '';
} }
}, };
onDelete() { const onSave = () => {
const items = ['name', 'tel'];
if (props.showArea) {
items.push('areaCode');
}
if (props.showDetail) {
items.push('addressDetail');
}
if (props.showPostal) {
items.push('postalCode');
}
const isValid = items.every((item) => {
const msg = getErrorMessage(item);
if (msg) {
state.errorInfo[item] = msg;
}
return !msg;
});
if (isValid && !props.isSaving) {
emit('save', state.data);
}
};
const onChangeDetail = (val) => {
state.data.addressDetail = val;
emit('change-detail', val);
};
const onAreaConfirm = (values) => {
values = values.filter((value) => !!value);
if (values.some((value) => !value.code)) {
Toast(t('areaEmpty'));
return;
}
state.showAreaPopup = false;
assignAreaValues();
emit('change-area', values);
};
const onDelete = () => {
Dialog.confirm({ Dialog.confirm({
title: t('confirmDelete'), title: t('confirmDelete'),
}) })
.then(() => { .then(() => {
this.$emit('delete', this.data); emit('delete', state.data);
}) })
.catch(() => { .catch(() => {
this.$emit('cancel-delete', this.data); emit('cancel-delete', state.data);
}); });
}, };
// get values of area component // get values of area component
getArea() { const getArea = () => (areaRef.value ? areaRef.value.getValues() : []);
return this.$refs.area ? this.$refs.area.getValues() : [];
},
// set area code to area component // set area code to area component
setAreaCode(code) { const setAreaCode = (code) => {
this.data.areaCode = code || ''; state.data.areaCode = code || '';
if (code) { if (code) {
this.$nextTick(this.assignAreaValues); nextTick(assignAreaValues);
} }
}, };
// @exposed-api const onDetailBlur = () => {
setAddressDetail(value) {
this.data.addressDetail = value;
},
onDetailBlur() {
// await for click search event // await for click search event
setTimeout(() => { setTimeout(() => {
this.detailFocused = false; state.detailFocused = false;
}); });
}, };
genSetDefaultCell(h) { const setAddressDetail = (value) => {
if (this.showSetDefault) { state.data.addressDetail = value;
};
const renderSetDefaultCell = () => {
if (props.showSetDefault) {
const slots = { const slots = {
'right-icon': () => ( 'right-icon': () => (
<Switch <Switch
vModel={this.data.isDefault} vModel={state.data.isDefault}
size="24" size="24"
onChange={(event) => { onChange={(event) => {
this.$emit('change-default', event); emit('change-default', event);
}} }}
/> />
), ),
@ -295,7 +274,7 @@ export default createComponent({
return ( return (
<Cell <Cell
v-slots={slots} v-slots={slots}
vShow={!this.hideBottomFields} vShow={!hideBottomFields.value}
center center
title={t('defaultAddress')} title={t('defaultAddress')}
class={bem('default')} class={bem('default')}
@ -304,12 +283,38 @@ export default createComponent({
} }
return h(); return h();
}, };
},
render(h) { useExpose({
const { data, errorInfo, disableArea, hideBottomFields } = this; getArea,
const onFocus = (name) => () => this.onFocus(name); setAddressDetail,
});
watch(
() => props.areaList,
() => {
setAreaCode(state.data.areaCode);
}
);
watch(
() => props.addressInfo,
(value) => {
state.data = {
...defaultData,
...value,
};
setAreaCode(value.areaCode);
},
{
deep: true,
immediate: true,
}
);
return () => {
const { data, errorInfo } = state;
const { disableArea } = props;
return ( return (
<div class={bem()}> <div class={bem()}>
@ -320,103 +325,104 @@ export default createComponent({
label={t('name')} label={t('name')}
placeholder={t('namePlaceholder')} placeholder={t('namePlaceholder')}
errorMessage={errorInfo.name} errorMessage={errorInfo.name}
onFocus={onFocus('name')} onFocus={() => onFocus('name')}
/> />
<Field <Field
vModel={data.tel} vModel={data.tel}
clearable clearable
type="tel" type="tel"
label={t('tel')} label={t('tel')}
maxlength={this.telMaxlength} maxlength={props.telMaxlength}
placeholder={t('telPlaceholder')} placeholder={t('telPlaceholder')}
errorMessage={errorInfo.tel} errorMessage={errorInfo.tel}
onFocus={onFocus('tel')} onFocus={() => onFocus('tel')}
/> />
<Field <Field
vShow={this.showArea} vShow={props.showArea}
readonly readonly
clickable={!disableArea}
label={t('area')} label={t('area')}
placeholder={this.areaPlaceholder || t('areaPlaceholder')} clickable={!disableArea}
errorMessage={errorInfo.areaCode}
rightIcon={!disableArea ? 'arrow' : null} rightIcon={!disableArea ? 'arrow' : null}
modelValue={this.areaText} modelValue={areaText.value}
onFocus={onFocus('areaCode')} placeholder={props.areaPlaceholder || t('areaPlaceholder')}
errorMessage={errorInfo.areaCode}
onFocus={() => onFocus('areaCode')}
onClick={() => { onClick={() => {
this.$emit('click-area'); emit('click-area');
this.showAreaPopup = !disableArea; state.showAreaPopup = !disableArea;
}} }}
/> />
<Detail <Detail
show={this.showDetail} show={props.showDetail}
value={data.addressDetail} value={data.addressDetail}
focused={this.detailFocused} focused={state.detailFocused}
detailRows={props.detailRows}
errorMessage={errorInfo.addressDetail} errorMessage={errorInfo.addressDetail}
detailRows={this.detailRows} searchResult={props.searchResult}
detailMaxlength={this.detailMaxlength} detailMaxlength={props.detailMaxlength}
searchResult={this.searchResult} showSearchResult={props.showSearchResult}
showSearchResult={this.showSearchResult} onBlur={onDetailBlur}
onBlur={this.onDetailBlur} onFocus={() => onFocus('addressDetail')}
onFocus={onFocus('addressDetail')} onInput={onChangeDetail}
onInput={this.onChangeDetail}
onSelect-search={(event) => { onSelect-search={(event) => {
this.$emit('select-search', event); emit('select-search', event);
}} }}
/> />
{this.showPostal && ( {props.showPostal && (
<Field <Field
vShow={!hideBottomFields} vShow={!hideBottomFields.value}
vModel={data.postalCode} vModel={data.postalCode}
type="tel" type="tel"
maxlength="6" maxlength="6"
label={t('postal')} label={t('postal')}
placeholder={t('postal')} placeholder={t('postal')}
errorMessage={errorInfo.postalCode} errorMessage={errorInfo.postalCode}
onFocus={onFocus('postalCode')} onFocus={() => onFocus('postalCode')}
/> />
)} )}
{this.$slots.default?.()} {slots.default?.()}
</div> </div>
{this.genSetDefaultCell(h)} {renderSetDefaultCell()}
<div vShow={!hideBottomFields} class={bem('buttons')}> <div vShow={!hideBottomFields.value} class={bem('buttons')}>
<Button <Button
block block
round round
loading={this.isSaving} loading={props.isSaving}
type="danger" type="danger"
text={this.saveButtonText || t('save')} text={props.saveButtonText || t('save')}
onClick={this.onSave} onClick={onSave}
/> />
{this.showDelete && ( {props.showDelete && (
<Button <Button
block block
round round
loading={this.isDeleting} loading={props.isDeleting}
text={this.deleteButtonText || t('delete')} text={props.deleteButtonText || t('delete')}
onClick={this.onDelete} onClick={onDelete}
/> />
)} )}
</div> </div>
<Popup <Popup
vModel={[this.showAreaPopup, 'show']} vModel={[state.showAreaPopup, 'show']}
round round
teleport="body" teleport="body"
position="bottom" position="bottom"
lazyRender={false} lazyRender={false}
> >
<Area <Area
ref="area" ref={areaRef}
value={data.areaCode} value={data.areaCode}
loading={!this.areaListLoaded} loading={!areaListLoaded.value}
areaList={this.areaList} areaList={props.areaList}
columnsPlaceholder={this.areaColumnsPlaceholder} columnsPlaceholder={props.areaColumnsPlaceholder}
onConfirm={this.onAreaConfirm} onConfirm={onAreaConfirm}
onCancel={() => { onCancel={() => {
this.showAreaPopup = false; state.showAreaPopup = false;
}} }}
/> />
</Popup> </Popup>
</div> </div>
); );
};
}, },
}); });