chore: prettier source code

This commit is contained in:
chenjiahan 2020-04-02 15:36:02 +08:00
parent 340c56b3b5
commit 2fb5cca49a
93 changed files with 272 additions and 283 deletions

View File

@ -53,7 +53,7 @@ export default createComponent({
genSearchResult() { genSearchResult() {
const { value, shouldShowSearchResult, searchResult } = this; const { value, shouldShowSearchResult, searchResult } = this;
if (shouldShowSearchResult) { if (shouldShowSearchResult) {
return searchResult.map(express => ( return searchResult.map((express) => (
<Cell <Cell
key={express.name + express.address} key={express.name + express.address}
clickable clickable

View File

@ -106,7 +106,7 @@ export default createComponent({
if (province && province === city) { if (province && province === city) {
arr.splice(1, 1); arr.splice(1, 1);
} }
return arr.filter(text => text).join('/'); return arr.filter((text) => text).join('/');
} }
return ''; return '';
}, },
@ -144,9 +144,9 @@ export default createComponent({
}, },
onAreaConfirm(values) { onAreaConfirm(values) {
values = values.filter(value => !!value); values = values.filter((value) => !!value);
if (values.some(value => !value.code)) { if (values.some((value) => !value.code)) {
Toast(t('areaEmpty')); Toast(t('areaEmpty'));
return; return;
} }
@ -182,7 +182,7 @@ export default createComponent({
items.push('postalCode'); items.push('postalCode');
} }
const isValid = items.every(item => { const isValid = items.every((item) => {
const msg = this.getErrorMessage(item); const msg = this.getErrorMessage(item);
if (msg) { if (msg) {
this.errorInfo[item] = msg; this.errorInfo[item] = msg;
@ -260,7 +260,7 @@ export default createComponent({
render() { render() {
const { data, errorInfo, searchResult, disableArea } = this; const { data, errorInfo, searchResult, disableArea } = this;
const onFocus = name => () => this.onFocus(name); const onFocus = (name) => () => this.onFocus(name);
// hide bottom field when use search && detail get focused // hide bottom field when use search && detail get focused
const hideBottomFields = const hideBottomFields =
@ -313,7 +313,7 @@ export default createComponent({
onFocus={onFocus('addressDetail')} onFocus={onFocus('addressDetail')}
onBlur={this.onDetailBlur} onBlur={this.onDetailBlur}
onInput={this.onChangeDetail} onInput={this.onChangeDetail}
onSelect-search={event => { onSelect-search={(event) => {
this.$emit('select-search', event); this.$emit('select-search', event);
}} }}
/> />
@ -337,7 +337,7 @@ export default createComponent({
vModel={data.isDefault} vModel={data.isDefault}
vShow={!hideBottomFields} vShow={!hideBottomFields}
title={t('defaultAddress')} title={t('defaultAddress')}
onChange={event => { onChange={(event) => {
this.$emit('change-default', event); this.$emit('change-default', event);
}} }}
/> />

View File

@ -14,7 +14,7 @@ function pickSlots(instance, keys) {
const { $slots, $scopedSlots } = instance; const { $slots, $scopedSlots } = instance;
const scopedSlots = {}; const scopedSlots = {};
keys.forEach(key => { keys.forEach((key) => {
if ($scopedSlots[key]) { if ($scopedSlots[key]) {
scopedSlots[key] = $scopedSlots[key]; scopedSlots[key] = $scopedSlots[key];
} else if ($slots[key]) { } else if ($slots[key]) {
@ -111,7 +111,7 @@ export default createComponent({
} }
const list = this[type]; const list = this[type];
result = Object.keys(list).map(listCode => ({ result = Object.keys(list).map((listCode) => ({
code: listCode, code: listCode,
name: list[listCode], name: list[listCode],
})); }));
@ -122,7 +122,7 @@ export default createComponent({
code = '9'; code = '9';
} }
result = result.filter(item => item.code.indexOf(code) === 0); result = result.filter((item) => item.code.indexOf(code) === 0);
} }
if (this.placeholderMap[type] && result.length) { if (this.placeholderMap[type] && result.length) {
@ -239,7 +239,9 @@ export default createComponent({
getValues() { getValues() {
const { picker } = this.$refs; const { picker } = this.$refs;
let getValues = picker ? picker.getValues().filter(value => !!value) : []; let getValues = picker
? picker.getValues().filter((value) => !!value)
: [];
getValues = this.parseOutputValues(getValues); getValues = this.parseOutputValues(getValues);
return getValues; return getValues;
}, },
@ -258,8 +260,8 @@ export default createComponent({
return area; return area;
} }
const names = values.map(item => item.name); const names = values.map((item) => item.name);
const validValues = values.filter(value => !!value.code); const validValues = values.filter((value) => !!value.code);
area.code = validValues.length area.code = validValues.length
? validValues[validValues.length - 1].code ? validValues[validValues.length - 1].code

View File

@ -70,17 +70,11 @@ test('change option', () => {
expect(wrapper).toMatchSnapshot(); expect(wrapper).toMatchSnapshot();
triggerDrag(columns.at(0), 0, -100); triggerDrag(columns.at(0), 0, -100);
columns columns.at(0).find('ul').trigger('transitionend');
.at(0)
.find('ul')
.trigger('transitionend');
expect(wrapper).toMatchSnapshot(); expect(wrapper).toMatchSnapshot();
triggerDrag(columns.at(2), 0, -100); triggerDrag(columns.at(2), 0, -100);
columns columns.at(2).find('ul').trigger('transitionend');
.at(2)
.find('ul')
.trigger('transitionend');
expect(wrapper).toMatchSnapshot(); expect(wrapper).toMatchSnapshot();
expect(onChange.mock.calls[0][1]).toEqual(secondOption); expect(onChange.mock.calls[0][1]).toEqual(secondOption);

View File

@ -30,7 +30,7 @@ export default createComponent({
return ( return (
<div class={bem('weekdays')}> <div class={bem('weekdays')}>
{weekdays.map(item => ( {weekdays.map((item) => (
<span class={bem('weekday')}>{item}</span> <span class={bem('weekday')}>{item}</span>
))} ))}
</div> </div>

View File

@ -99,8 +99,8 @@ export default createComponent({
}, },
getMultipleDayType(day) { getMultipleDayType(day) {
const isSelected = date => const isSelected = (date) =>
this.currentDate.some(item => compareDay(item, date) === 0); this.currentDate.some((item) => compareDay(item, date) === 0);
if (isSelected(day)) { if (isSelected(day)) {
const prevDay = getPrevDay(day); const prevDay = getPrevDay(day);

View File

@ -125,7 +125,7 @@ export default {
youthDay: '青年节', youthDay: '青年节',
calendar: '日历', calendar: '日历',
maxRange: '日期区间最大范围', maxRange: '日期区间最大范围',
selectCount: count => `选择了 ${count} 个日期`, selectCount: (count) => `选择了 ${count} 个日期`,
selectSingle: '选择单个日期', selectSingle: '选择单个日期',
selectMultiple: '选择多个日期', selectMultiple: '选择多个日期',
selectRange: '选择日期区间', selectRange: '选择日期区间',
@ -148,7 +148,7 @@ export default {
youthDay: 'Youth Day', youthDay: 'Youth Day',
calendar: 'Calendar', calendar: 'Calendar',
maxRange: 'Max Range', maxRange: 'Max Range',
selectCount: count => `${count} dates selected`, selectCount: (count) => `${count} dates selected`,
selectSingle: 'Select Single Date', selectSingle: 'Select Single Date',
selectMultiple: 'Select Multiple Date', selectMultiple: 'Select Multiple Date',
selectRange: 'Select Date Range', selectRange: 'Select Date Range',

View File

@ -219,7 +219,7 @@ export default createComponent({
const { body, months } = this.$refs; const { body, months } = this.$refs;
const top = getScrollTop(body); const top = getScrollTop(body);
const bottom = top + this.bodyHeight; const bottom = top + this.bodyHeight;
const heights = months.map(item => item.height); const heights = months.map((item) => item.height);
const heightSum = heights.reduce((a, b) => a + b, 0); const heightSum = heights.reduce((a, b) => a + b, 0);
// iOS scroll bounce may exceed the range // iOS scroll bounce may exceed the range
@ -412,7 +412,7 @@ export default createComponent({
render() { render() {
if (this.poppable) { if (this.poppable) {
const createListener = name => () => this.$emit(name); const createListener = (name) => () => this.$emit(name);
return ( return (
<Popup <Popup

View File

@ -33,10 +33,7 @@ test('select event when type is single', async () => {
await later(); await later();
wrapper wrapper.findAll('.van-calendar__day').at(15).trigger('click');
.findAll('.van-calendar__day')
.at(15)
.trigger('click');
expect(formatDate(wrapper.emitted('select')[0][0])).toEqual('2010/1/16'); expect(formatDate(wrapper.emitted('select')[0][0])).toEqual('2010/1/16');
}); });
@ -112,10 +109,7 @@ test('should not trigger select event when click disabled day', async () => {
await later(); await later();
wrapper wrapper.findAll('.van-calendar__day').at(1).trigger('click');
.findAll('.van-calendar__day')
.at(1)
.trigger('click');
expect(formatDate(wrapper.emitted('select'))).toBeFalsy(); expect(formatDate(wrapper.emitted('select'))).toBeFalsy();
}); });
@ -131,10 +125,7 @@ test('confirm event when type is single', async () => {
await later(); await later();
wrapper wrapper.findAll('.van-calendar__day').at(15).trigger('click');
.findAll('.van-calendar__day')
.at(15)
.trigger('click');
expect(wrapper.emitted('confirm')).toBeFalsy(); expect(wrapper.emitted('confirm')).toBeFalsy();
@ -446,7 +437,7 @@ test('color prop when type is range', async () => {
expect(wrapper).toMatchSnapshot(); expect(wrapper).toMatchSnapshot();
}); });
test('should scroll to current month when show', async done => { test('should scroll to current month when show', async (done) => {
const wrapper = mount(Calendar, { const wrapper = mount(Calendar, {
propsData: { propsData: {
type: 'range', type: 'range',
@ -456,7 +447,7 @@ test('should scroll to current month when show', async done => {
}, },
}); });
Element.prototype.scrollIntoView = function() { Element.prototype.scrollIntoView = function () {
expect(this.parentNode).toEqual( expect(this.parentNode).toEqual(
wrapper.findAll('.van-calendar__month').at(3).element wrapper.findAll('.van-calendar__month').at(3).element
); );

View File

@ -59,7 +59,7 @@ export function calcDateNum(date: [Date, Date]) {
export function copyDates(dates: Date | Date[]) { export function copyDates(dates: Date | Date[]) {
if (Array.isArray(dates)) { if (Array.isArray(dates)) {
return dates.map(date => { return dates.map((date) => {
if (date === null) { if (date === null) {
return date; return date;
} }

View File

@ -35,10 +35,10 @@ export default createComponent({
let { children } = this; let { children } = this;
if (!checked) { if (!checked) {
children = children.filter(item => !item.checked); children = children.filter((item) => !item.checked);
} }
const names = children.map(item => item.name); const names = children.map((item) => item.name);
this.$emit('input', names); this.$emit('input', names);
}, },
}, },

View File

@ -4,7 +4,7 @@ import { mount, later } from '../../../test';
test('switch checkbox', async () => { test('switch checkbox', async () => {
const wrapper = mount(Checkbox); const wrapper = mount(Checkbox);
wrapper.vm.$on('input', value => { wrapper.vm.$on('input', (value) => {
wrapper.setData({ value }); wrapper.setData({ value });
}); });

View File

@ -70,7 +70,7 @@
</template> </template>
<script> <script>
const format = rate => Math.min(Math.max(rate, 0), 100); const format = (rate) => Math.min(Math.max(rate, 0), 100);
export default { export default {
i18n: { i18n: {

View File

@ -14,8 +14,9 @@ function format(rate) {
function getPath(clockwise, viewBoxSize) { function getPath(clockwise, viewBoxSize) {
const sweepFlag = clockwise ? 1 : 0; const sweepFlag = clockwise ? 1 : 0;
return `M ${viewBoxSize / 2} ${viewBoxSize / return `M ${viewBoxSize / 2} ${
2} m 0, -500 a 500, 500 0 1, ${sweepFlag} 0, 1000 a 500, 500 0 1, ${sweepFlag} 0, -1000`; viewBoxSize / 2
} m 0, -500 a 500, 500 0 1, ${sweepFlag} 0, 1000 a 500, 500 0 1, ${sweepFlag} 0, -1000`;
} }
export default createComponent({ export default createComponent({

View File

@ -57,7 +57,7 @@ export default createComponent({
return accordion return accordion
? value === this.currentName ? value === this.currentName
: value.some(name => name === this.currentName); : value.some((name) => name === this.currentName);
}, },
}, },

View File

@ -21,7 +21,7 @@ export default createComponent({
if (!this.accordion) { if (!this.accordion) {
name = expanded name = expanded
? this.value.concat(name) ? this.value.concat(name)
: this.value.filter(activeName => activeName !== name); : this.value.filter((activeName) => activeName !== name);
} }
this.$emit('change', name); this.$emit('change', name);
this.$emit('input', name); this.$emit('input', name);

View File

@ -84,7 +84,7 @@ export default {
currentContact() { currentContact() {
const id = this.chosenContactId; const id = this.chosenContactId;
return id !== null ? this.list.filter(item => item.id === id)[0] : {}; return id !== null ? this.list.filter((item) => item.id === id)[0] : {};
}, },
}, },
@ -114,7 +114,9 @@ export default {
this.showList = false; this.showList = false;
if (this.isEdit) { if (this.isEdit) {
this.list = this.list.map(item => (item.id === info.id ? info : item)); this.list = this.list.map((item) =>
(item.id === info.id ? info : item)
);
} else { } else {
this.list.push(info); this.list.push(info);
} }
@ -123,7 +125,7 @@ export default {
onDelete(info) { onDelete(info) {
this.showEdit = false; this.showEdit = false;
this.list = this.list.filter(item => item.id !== info.id); this.list = this.list.filter((item) => item.id !== info.id);
if (this.chosenContactId === info.id) { if (this.chosenContactId === info.id) {
this.chosenContactId = null; this.chosenContactId = null;
} }

View File

@ -71,7 +71,7 @@ export default createComponent({
}, },
onSave() { onSave() {
const isValid = ['name', 'tel'].every(item => { const isValid = ['name', 'tel'].every((item) => {
const msg = this.getErrorMessageByKey(item); const msg = this.getErrorMessageByKey(item);
if (msg) { if (msg) {
this.errorInfo[item] = msg; this.errorInfo[item] = msg;
@ -95,7 +95,7 @@ export default createComponent({
render() { render() {
const { data, errorInfo } = this; const { data, errorInfo } = this;
const onFocus = name => () => this.onFocus(name); const onFocus = (name) => () => this.onFocus(name);
return ( return (
<div class={bem()}> <div class={bem()}>
@ -128,7 +128,7 @@ export default createComponent({
<Switch <Switch
vModel={data.isDefault} vModel={data.isDefault}
size={24} size={24}
onChange={event => { onChange={(event) => {
this.$emit('change-default', event); this.$emit('change-default', event);
}} }}
/> />

View File

@ -61,7 +61,7 @@ function ContactList(
<Icon <Icon
name="edit" name="edit"
class={bem('edit')} class={bem('edit')}
onClick={event => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
emit(ctx, 'edit', item, index); emit(ctx, 'edit', item, index);
}} }}

View File

@ -181,7 +181,7 @@ export default createComponent({
</div> </div>
); );
const onChange = index => () => this.$emit('change', index); const onChange = (index) => () => this.$emit('change', index);
const CouponTab = ( const CouponTab = (
<Tab title={title}> <Tab title={title}>
@ -210,7 +210,7 @@ export default createComponent({
class={bem('list', { 'with-bottom': this.showCloseButton })} class={bem('list', { 'with-bottom': this.showCloseButton })}
style={this.listStyle} style={this.listStyle}
> >
{disabledCoupons.map(coupon => ( {disabledCoupons.map((coupon) => (
<Coupon <Coupon
disabled disabled
key={coupon.id} key={coupon.id}

View File

@ -105,10 +105,7 @@ test('render empty coupon list', () => {
disabledCoupons: [], disabledCoupons: [],
}, },
}); });
wrapper wrapper.findAll('.van-tab').at(1).trigger('click');
.findAll('.van-tab')
.at(1)
.trigger('click');
expect(wrapper).toMatchSnapshot(); expect(wrapper).toMatchSnapshot();
}); });

View File

@ -141,7 +141,7 @@ export default createComponent({
updateInnerValue() { updateInnerValue() {
const indexes = this.getPicker().getIndexes(); const indexes = this.getPicker().getIndexes();
const getValue = index => { const getValue = (index) => {
const { values } = this.originColumns[index]; const { values } = this.originColumns[index];
return getTrueValue(values[indexes[index]]); return getTrueValue(values[indexes[index]]);
}; };

View File

@ -95,7 +95,7 @@ export default {
filter(type, values) { filter(type, values) {
if (type === 'minute') { if (type === 'minute') {
return values.filter(value => value % 5 === 0); return values.filter((value) => value % 5 === 0);
} }
return values; return values;

View File

@ -27,7 +27,7 @@ export const TimePickerMixin = {
computed: { computed: {
originColumns() { originColumns() {
return this.ranges.map(({ type, range: rangeArr }) => { return this.ranges.map(({ type, range: rangeArr }) => {
let values = times(rangeArr[1] - rangeArr[0] + 1, index => { let values = times(rangeArr[1] - rangeArr[0] + 1, (index) => {
const value = padZero(rangeArr[0] + index); const value = padZero(rangeArr[0] + index);
return value; return value;
}); });
@ -44,8 +44,10 @@ export const TimePickerMixin = {
}, },
columns() { columns() {
return this.originColumns.map(column => ({ return this.originColumns.map((column) => ({
values: column.values.map(value => this.formatter(column.type, value)), values: column.values.map((value) =>
this.formatter(column.type, value)
),
})); }));
}, },
}, },
@ -83,7 +85,7 @@ export const TimePickerMixin = {
render() { render() {
const props = {}; const props = {};
Object.keys(pickerProps).forEach(key => { Object.keys(pickerProps).forEach((key) => {
props[key] = this[key]; props[key] = this[key];
}); });

View File

@ -3,7 +3,7 @@ import { mount, later, triggerDrag } from '../../../test';
function filter(type, options) { function filter(type, options) {
const mod = type === 'year' ? 10 : 5; const mod = type === 'year' ? 10 : 5;
return options.filter(option => option % mod === 0); return options.filter((option) => option % mod === 0);
} }
function formatter(type, value) { function formatter(type, value) {
@ -128,7 +128,7 @@ test('use min-date with filter', async () => {
value: new Date(2020, 0, 0, 0, 0), value: new Date(2020, 0, 0, 0, 0),
filter(type, values) { filter(type, values) {
if (type === 'minute') { if (type === 'minute') {
return values.filter(value => value % 30 === 0); return values.filter((value) => value % 30 === 0);
} }
return values; return values;

View File

@ -3,7 +3,7 @@ import { mount, later, triggerDrag } from '../../../test';
function filter(type, options) { function filter(type, options) {
const mod = type === 'minute' ? 10 : 5; const mod = type === 'minute' ? 10 : 5;
return options.filter(option => option % mod === 0); return options.filter((option) => option % mod === 0);
} }
function formatter(type, value) { function formatter(type, value) {

View File

@ -63,7 +63,7 @@ export default createComponent({
if (this.beforeClose) { if (this.beforeClose) {
this.loading[action] = true; this.loading[action] = true;
this.beforeClose(action, state => { this.beforeClose(action, (state) => {
if (state !== false && this.loading[action]) { if (state !== false && this.loading[action]) {
this.onClose(action); this.onClose(action);
} }

View File

@ -21,7 +21,7 @@ function initInstance() {
}, },
}); });
instance.$on('input', value => { instance.$on('input', (value) => {
instance.value = value; instance.value = value;
}); });
} }
@ -66,14 +66,14 @@ Dialog.defaultOptions = {
showCancelButton: false, showCancelButton: false,
closeOnPopstate: false, closeOnPopstate: false,
closeOnClickOverlay: false, closeOnClickOverlay: false,
callback: action => { callback: (action) => {
instance[action === 'confirm' ? 'resolve' : 'reject'](action); instance[action === 'confirm' ? 'resolve' : 'reject'](action);
}, },
}; };
Dialog.alert = Dialog; Dialog.alert = Dialog;
Dialog.confirm = options => Dialog.confirm = (options) =>
Dialog({ Dialog({
showCancelButton: true, showCancelButton: true,
...options, ...options,
@ -85,7 +85,7 @@ Dialog.close = () => {
} }
}; };
Dialog.setDefaultOptions = options => { Dialog.setDefaultOptions = (options) => {
Object.assign(Dialog.currentOptions, options); Object.assign(Dialog.currentOptions, options);
}; };

View File

@ -41,7 +41,9 @@ export default createComponent({
return this.title; return this.title;
} }
const match = this.options.filter(option => option.value === this.value); const match = this.options.filter(
(option) => option.value === this.value
);
return match.length ? match[0].text : ''; return match.length ? match[0].text : '';
}, },
}, },
@ -53,7 +55,7 @@ export default createComponent({
}, },
beforeCreate() { beforeCreate() {
const createEmitter = eventName => () => this.$emit(eventName); const createEmitter = (eventName) => () => this.$emit(eventName);
this.onOpen = createEmitter('open'); this.onOpen = createEmitter('open');
this.onClose = createEmitter('close'); this.onClose = createEmitter('close');
@ -105,7 +107,7 @@ export default createComponent({
closeOnClickOverlay, closeOnClickOverlay,
} = this.parent; } = this.parent;
const Options = this.options.map(option => { const Options = this.options.map((option) => {
const active = option.value === this.value; const active = option.value === this.value;
return ( return (
<Cell <Cell

View File

@ -77,7 +77,7 @@ export default createComponent({
}, },
onClickOutside() { onClickOutside() {
this.children.forEach(item => { this.children.forEach((item) => {
item.toggle(false); item.toggle(false);
}); });
}, },

View File

@ -213,7 +213,7 @@ test('change event', async () => {
expect(onChange).toHaveBeenCalledTimes(1); expect(onChange).toHaveBeenCalledTimes(1);
}); });
test('toggle method', async done => { test('toggle method', async (done) => {
const wrapper = mount({ const wrapper = mount({
template: ` template: `
<van-dropdown-menu> <van-dropdown-menu>

View File

@ -154,7 +154,7 @@ export default createComponent({
}, },
runValidator(value, rule) { runValidator(value, rule) {
return new Promise(resolve => { return new Promise((resolve) => {
const returnVal = rule.validator(value, rule); const returnVal = rule.validator(value, rule);
if (isPromise(returnVal)) { if (isPromise(returnVal)) {
@ -213,7 +213,7 @@ export default createComponent({
} }
if (rule.validator) { if (rule.validator) {
return this.runValidator(value, rule).then(result => { return this.runValidator(value, rule).then((result) => {
if (result === false) { if (result === false) {
this.validateMessage = this.getRuleMessage(value, rule); this.validateMessage = this.getRuleMessage(value, rule);
} }
@ -225,7 +225,7 @@ export default createComponent({
}, },
validate(rules = this.rules) { validate(rules = this.rules) {
return new Promise(resolve => { return new Promise((resolve) => {
if (!rules) { if (!rules) {
resolve(); resolve();
} }
@ -246,7 +246,7 @@ export default createComponent({
validateWithTrigger(trigger) { validateWithTrigger(trigger) {
if (this.vanForm && this.rules) { if (this.vanForm && this.rules) {
const defaultTrigger = this.vanForm.validateTrigger === trigger; const defaultTrigger = this.vanForm.validateTrigger === trigger;
const rules = this.rules.filter(rule => { const rules = this.rules.filter((rule) => {
if (rule.trigger) { if (rule.trigger) {
return rule.trigger === trigger; return rule.trigger === trigger;
} }

View File

@ -267,7 +267,7 @@ test('formatter prop', () => {
const wrapper = mount(Field, { const wrapper = mount(Field, {
propsData: { propsData: {
value: 'abc123', value: 'abc123',
formatter: value => value.replace(/\d/g, ''), formatter: (value) => value.replace(/\d/g, ''),
}, },
}); });
@ -301,7 +301,7 @@ test('name prop', () => {
expect(wrapper).toMatchSnapshot(); expect(wrapper).toMatchSnapshot();
}); });
test('call focus method before mounted', done => { test('call focus method before mounted', (done) => {
mount(Field, { mount(Field, {
created() { created() {
this.focus(); this.focus();

View File

@ -47,7 +47,7 @@ export default {
methods: { methods: {
onConfirm(values) { onConfirm(values) {
this.value = values.map(item => item.name).join('/'); this.value = values.map((item) => item.name).join('/');
this.showArea = false; this.showArea = false;
}, },

View File

@ -71,7 +71,7 @@ export default {
}, },
asyncValidator(val) { asyncValidator(val) {
return new Promise(resolve => { return new Promise((resolve) => {
this.$toast.loading(this.t('validating')); this.$toast.loading(this.t('validating'));
setTimeout(() => { setTimeout(() => {

View File

@ -48,7 +48,7 @@ export default createComponent({
(promise, field) => (promise, field) =>
promise.then(() => { promise.then(() => {
if (!errors.length) { if (!errors.length) {
return field.validate().then(error => { return field.validate().then((error) => {
if (error) { if (error) {
errors.push(error); errors.push(error);
} }
@ -69,15 +69,17 @@ export default createComponent({
validateAll() { validateAll() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
Promise.all(this.fields.map(item => item.validate())).then(errors => { Promise.all(this.fields.map((item) => item.validate())).then(
errors = errors.filter(item => item); (errors) => {
errors = errors.filter((item) => item);
if (errors.length) { if (errors.length) {
reject(errors); reject(errors);
} else { } else {
resolve(); resolve();
}
} }
}); );
}); });
}, },
@ -90,11 +92,11 @@ export default createComponent({
}, },
validateField(name) { validateField(name) {
const matched = this.fields.filter(item => item.name === name); const matched = this.fields.filter((item) => item.name === name);
if (matched.length) { if (matched.length) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
matched[0].validate().then(error => { matched[0].validate().then((error) => {
if (error) { if (error) {
reject(error); reject(error);
} else { } else {
@ -109,7 +111,7 @@ export default createComponent({
// @exposed-api // @exposed-api
resetValidation(name) { resetValidation(name) {
this.fields.forEach(item => { this.fields.forEach((item) => {
if (!name || item.name === name) { if (!name || item.name === name) {
item.resetValidation(); item.resetValidation();
} }
@ -118,7 +120,7 @@ export default createComponent({
// @exposed-api // @exposed-api
scrollToField(name) { scrollToField(name) {
this.fields.forEach(item => { this.fields.forEach((item) => {
if (item.name === name) { if (item.name === name) {
item.$el.scrollIntoView(); item.$el.scrollIntoView();
} }
@ -131,7 +133,7 @@ export default createComponent({
}, },
removeField(field) { removeField(field) {
this.fields = this.fields.filter(item => item !== field); this.fields = this.fields.filter((item) => item !== field);
}, },
getValues() { getValues() {
@ -154,7 +156,7 @@ export default createComponent({
.then(() => { .then(() => {
this.$emit('submit', values); this.$emit('submit', values);
}) })
.catch(errors => { .catch((errors) => {
this.$emit('failed', { this.$emit('failed', {
values, values,
errors, errors,

View File

@ -23,10 +23,10 @@ test('submit method', async () => {
expect(onSubmit).toHaveBeenCalledWith({ A: 'bar' }); expect(onSubmit).toHaveBeenCalledWith({ A: 'bar' });
}); });
test('validate method - validate all fields', done => { test('validate method - validate all fields', (done) => {
mountSimpleRulesForm({ mountSimpleRulesForm({
mounted() { mounted() {
this.$refs.form.validate().catch(err => { this.$refs.form.validate().catch((err) => {
expect(err).toEqual([ expect(err).toEqual([
{ message: 'A failed', name: 'A' }, { message: 'A failed', name: 'A' },
{ message: 'B failed', name: 'B' }, { message: 'B failed', name: 'B' },
@ -37,10 +37,10 @@ test('validate method - validate all fields', done => {
}); });
}); });
test('validate method - validate one field and passed', done => { test('validate method - validate one field and passed', (done) => {
mountSimpleRulesForm({ mountSimpleRulesForm({
mounted() { mounted() {
this.$refs.form.validate('A').catch(err => { this.$refs.form.validate('A').catch((err) => {
expect(err).toEqual({ message: 'A failed', name: 'A' }); expect(err).toEqual({ message: 'A failed', name: 'A' });
done(); done();
}); });
@ -48,7 +48,7 @@ test('validate method - validate one field and passed', done => {
}); });
}); });
test('validate method - validate one field and failed', done => { test('validate method - validate one field and failed', (done) => {
mountForm({ mountForm({
template: ` template: `
<van-form ref="form" @failed="onFailed"> <van-form ref="form" @failed="onFailed">
@ -64,7 +64,7 @@ test('validate method - validate one field and failed', done => {
}); });
}); });
test('validate method - unexisted name', done => { test('validate method - unexisted name', (done) => {
mountSimpleRulesForm({ mountSimpleRulesForm({
mounted() { mounted() {
this.$refs.form.validate('unexisted').catch(done); this.$refs.form.validate('unexisted').catch(done);
@ -72,7 +72,7 @@ test('validate method - unexisted name', done => {
}); });
}); });
test('resetValidation method - reset all fields', done => { test('resetValidation method - reset all fields', (done) => {
const wrapper = mountSimpleRulesForm({ const wrapper = mountSimpleRulesForm({
mounted() { mounted() {
this.$refs.form.validate().catch(() => { this.$refs.form.validate().catch(() => {
@ -85,7 +85,7 @@ test('resetValidation method - reset all fields', done => {
}); });
}); });
test('resetValidation method - reset one field', done => { test('resetValidation method - reset one field', (done) => {
const wrapper = mountSimpleRulesForm({ const wrapper = mountSimpleRulesForm({
mounted() { mounted() {
this.$refs.form.validate().catch(() => { this.$refs.form.validate().catch(() => {
@ -97,7 +97,7 @@ test('resetValidation method - reset one field', done => {
}); });
}); });
test('scrollToField method', done => { test('scrollToField method', (done) => {
const fn = mockScrollIntoView(); const fn = mockScrollIntoView();
mountSimpleRulesForm({ mountSimpleRulesForm({
mounted() { mounted() {

View File

@ -14,8 +14,8 @@ test('rules prop - execute order', async () => {
return { return {
rules: [ rules: [
{ required: true, message: 'A' }, { required: true, message: 'A' },
{ validator: val => val.length > 6, message: 'B' }, { validator: (val) => val.length > 6, message: 'B' },
{ validator: val => val !== 'foo', message: 'C' }, { validator: (val) => val !== 'foo', message: 'C' },
], ],
}; };
}, },
@ -70,7 +70,7 @@ test('rules prop - message function', async () => {
`, `,
data() { data() {
return { return {
rules: [{ pattern: /\d{6}/, message: val => val }], rules: [{ pattern: /\d{6}/, message: (val) => val }],
}; };
}, },
methods: { methods: {
@ -138,12 +138,12 @@ test('rules prop - async validator', async () => {
validator: (value, rule) => { validator: (value, rule) => {
expect(value).toEqual('123'); expect(value).toEqual('123');
expect(typeof rule).toEqual('object'); expect(typeof rule).toEqual('object');
return new Promise(resolve => resolve(true)); return new Promise((resolve) => resolve(true));
}, },
message: 'should pass', message: 'should pass',
}, },
{ {
validator: () => new Promise(resolve => resolve(false)), validator: () => new Promise((resolve) => resolve(false)),
message: 'should fail', message: 'should fail',
}, },
], ],

View File

@ -102,8 +102,9 @@ export default createComponent({
}; };
if (scale !== 1) { if (scale !== 1) {
style.transform = `scale3d(${scale}, ${scale}, 1) translate(${this style.transform = `scale3d(${scale}, ${scale}, 1) translate(${
.moveX / scale}px, ${this.moveY / scale}px)`; this.moveX / scale
}px, ${this.moveY / scale}px)`;
} }
return style; return style;

View File

@ -53,7 +53,7 @@ export default {
button3: '异步关闭', button3: '异步关闭',
button4: '展示关闭按钮', button4: '展示关闭按钮',
componentCall: '组件调用', componentCall: '组件调用',
index: index => `${index + 1}`, index: (index) => `${index + 1}`,
}, },
'en-US': { 'en-US': {
button1: 'Show Images', button1: 'Show Images',
@ -61,7 +61,7 @@ export default {
button3: 'Async Close', button3: 'Async Close',
button4: 'Show Close Icon', button4: 'Show Close Icon',
componentCall: 'Component Call', componentCall: 'Component Call',
index: index => `Page: ${index}`, index: (index) => `Page: ${index}`,
}, },
}, },

View File

@ -30,13 +30,13 @@ const initInstance = () => {
}); });
document.body.appendChild(instance.$el); document.body.appendChild(instance.$el);
instance.$on('change', index => { instance.$on('change', (index) => {
if (instance.onChange) { if (instance.onChange) {
instance.onChange(index); instance.onChange(index);
} }
}); });
instance.$on('scale', data => { instance.$on('scale', (data) => {
if (instance.onScale) { if (instance.onScale) {
instance.onScale(data); instance.onScale(data);
} }
@ -57,7 +57,7 @@ const ImagePreview = (images, startPosition = 0) => {
Object.assign(instance, defaultConfig, options); Object.assign(instance, defaultConfig, options);
instance.$once('input', show => { instance.$once('input', (show) => {
instance.value = show; instance.value = show;
}); });

View File

@ -103,7 +103,7 @@ test('async close prop', async () => {
expect(wrapper.emitted('close')[0]).toBeTruthy(); expect(wrapper.emitted('close')[0]).toBeTruthy();
}); });
test('function call', done => { test('function call', (done) => {
ImagePreview(images); ImagePreview(images);
ImagePreview(images.slice(0, 1)); ImagePreview(images.slice(0, 1));
Vue.nextTick(() => { Vue.nextTick(() => {
@ -116,7 +116,7 @@ test('function call', done => {
}); });
}); });
test('double click', async done => { test('double click', async (done) => {
const instance = ImagePreview(images); const instance = ImagePreview(images);
await later(); await later();
@ -150,7 +150,7 @@ test('onClose option', () => {
}); });
}); });
test('onChange option', async done => { test('onChange option', async (done) => {
const instance = ImagePreview({ const instance = ImagePreview({
images, images,
startPostion: 0, startPostion: 0,
@ -164,7 +164,7 @@ test('onChange option', async done => {
triggerDrag(swipe, 1000, 0); triggerDrag(swipe, 1000, 0);
}); });
test('onScale option', async done => { test('onScale option', async (done) => {
const { getBoundingClientRect } = Element.prototype; const { getBoundingClientRect } = Element.prototype;
Element.prototype.getBoundingClientRect = jest.fn(() => ({ width: 100 })); Element.prototype.getBoundingClientRect = jest.fn(() => ({ width: 100 }));

View File

@ -48,7 +48,7 @@ test('lazy load', () => {
expect(wrapper).toMatchSnapshot(); expect(wrapper).toMatchSnapshot();
}); });
test('lazy-load load event', done => { test('lazy-load load event', (done) => {
const wrapper = mount(Image, { const wrapper = mount(Image, {
propsData: { propsData: {
lazyLoad: true, lazyLoad: true,
@ -75,7 +75,7 @@ test('lazy-load load event', done => {
}); });
}); });
test('lazy-load error event', done => { test('lazy-load error event', (done) => {
const wrapper = mount(Image, { const wrapper = mount(Image, {
propsData: { propsData: {
lazyLoad: true, lazyLoad: true,

View File

@ -32,7 +32,7 @@ export default createComponent({
mixins: [ mixins: [
TouchMixin, TouchMixin,
ParentMixin('vanIndexBar'), ParentMixin('vanIndexBar'),
BindEventMixin(function(bind) { BindEventMixin(function (bind) {
if (!this.scroller) { if (!this.scroller) {
this.scroller = getScroller(this.$el); this.scroller = getScroller(this.$el);
} }
@ -97,7 +97,7 @@ export default createComponent({
const scrollTop = getScrollTop(this.scroller); const scrollTop = getScrollTop(this.scroller);
const scrollerRect = this.getScrollerRect(); const scrollerRect = this.getScrollerRect();
const rects = this.children.map(item => ({ const rects = this.children.map((item) => ({
height: item.height, height: item.height,
top: this.getElementTop(item.$el, scrollerRect), top: this.getElementTop(item.$el, scrollerRect),
})); }));
@ -198,7 +198,9 @@ export default createComponent({
return; return;
} }
const match = this.children.filter(item => String(item.index) === index); const match = this.children.filter(
(item) => String(item.index) === index
);
if (match[0]) { if (match[0]) {
match[0].scrollIntoView(); match[0].scrollIntoView();
@ -216,7 +218,7 @@ export default createComponent({
}, },
render() { render() {
const Indexes = this.indexList.map(index => { const Indexes = this.indexList.map((index) => {
const active = index === this.activeAnchorIndex; const active = index === this.activeAnchorIndex;
return ( return (

View File

@ -62,7 +62,7 @@ test('touch and scroll to anchor', () => {
const sidebar = wrapper.find('.van-index-bar__sidebar'); const sidebar = wrapper.find('.van-index-bar__sidebar');
const indexes = wrapper.findAll('.van-index-bar__index'); const indexes = wrapper.findAll('.van-index-bar__index');
document.elementFromPoint = function(x, y) { document.elementFromPoint = function (x, y) {
const index = y / 100; const index = y / 100;
if (index === 1 || index === 2) { if (index === 1 || index === 2) {
@ -93,7 +93,7 @@ test('touch and scroll to anchor', () => {
test('scroll and update active anchor', () => { test('scroll and update active anchor', () => {
const nativeRect = Element.prototype.getBoundingClientRect; const nativeRect = Element.prototype.getBoundingClientRect;
Element.prototype.getBoundingClientRect = function() { Element.prototype.getBoundingClientRect = function () {
const { index } = this.dataset; const { index } = this.dataset;
return { return {
top: index ? index * 10 : 0, top: index ? index * 10 : 0,

View File

@ -13,7 +13,7 @@ const [createComponent, bem, t] = createNamespace('list');
export default createComponent({ export default createComponent({
mixins: [ mixins: [
BindEventMixin(function(bind) { BindEventMixin(function (bind) {
if (!this.scroller) { if (!this.scroller) {
this.scroller = getScroller(this.$el); this.scroller = getScroller(this.$el);
} }

View File

@ -4,7 +4,7 @@ import { mount, later, mockGetBoundingClientRect } from '../../../test';
test('load event', async () => { test('load event', async () => {
const wrapper = mount(List); const wrapper = mount(List);
wrapper.vm.$on('input', value => { wrapper.vm.$on('input', (value) => {
wrapper.vm.loading = value; wrapper.vm.loading = value;
}); });
@ -33,7 +33,7 @@ test('error loaded, click error-text and reload', async () => {
expect(wrapper.emitted('input')).toBeFalsy(); expect(wrapper.emitted('input')).toBeFalsy();
// simulate the behavior of clicking error-text // simulate the behavior of clicking error-text
wrapper.vm.$on('update:error', val => { wrapper.vm.$on('update:error', (val) => {
wrapper.setProps({ wrapper.setProps({
error: val, error: val,
}); });

View File

@ -3,7 +3,7 @@ import { BindEventMixin } from './bind-event';
export const CloseOnPopstateMixin = { export const CloseOnPopstateMixin = {
mixins: [ mixins: [
BindEventMixin(function(bind, isBind) { BindEventMixin(function (bind, isBind) {
this.handlePopstate(isBind && this.closeOnPopstate); this.handlePopstate(isBind && this.closeOnPopstate);
}), }),
], ],

View File

@ -63,7 +63,7 @@ export function updateOverlay(): void {
} }
export function openOverlay(vm: any, config: OverlayConfig): void { export function openOverlay(vm: any, config: OverlayConfig): void {
if (!context.stack.some(item => item.vm === vm)) { if (!context.stack.some((item) => item.vm === vm)) {
context.stack.push({ vm, config }); context.stack.push({ vm, config });
updateOverlay(); updateOverlay();
} }
@ -77,7 +77,7 @@ export function closeOverlay(vm: any): void {
stack.pop(); stack.pop();
updateOverlay(); updateOverlay();
} else { } else {
context.stack = stack.filter(item => item.vm !== vm); context.stack = stack.filter((item) => item.vm !== vm);
} }
} }
} }

View File

@ -133,7 +133,7 @@ export default createComponent({
vShow={this.showNoticeBar} vShow={this.showNoticeBar}
class={bem({ wrapable: this.wrapable })} class={bem({ wrapable: this.wrapable })}
style={barStyle} style={barStyle}
onClick={event => { onClick={(event) => {
this.$emit('click', event); this.$emit('click', event);
}} }}
> >

View File

@ -10,7 +10,7 @@ const DELETE_KEY_THEME = ['delete', 'big', 'gray'];
export default createComponent({ export default createComponent({
mixins: [ mixins: [
BindEventMixin(function(bind) { BindEventMixin(function (bind) {
if (this.hideOnClickOutside) { if (this.hideOnClickOutside) {
bind(document.body, 'touchstart', this.onBlur); bind(document.body, 'touchstart', this.onBlur);
} }
@ -165,7 +165,7 @@ export default createComponent({
}, },
genKeys() { genKeys() {
return this.keys.map(key => ( return this.keys.map((key) => (
<Key <Key
key={key.text} key={key.text}
text={key.text} text={key.text}

View File

@ -151,7 +151,7 @@ test('bind value', () => {
value: '', value: '',
}, },
listeners: { listeners: {
'update:value': value => { 'update:value': (value) => {
wrapper.setProps({ value }); wrapper.setProps({ value });
}, },
}, },
@ -176,7 +176,7 @@ test('maxlength', () => {
}, },
listeners: { listeners: {
input: onInput, input: onInput,
'update:value': value => { 'update:value': (value) => {
wrapper.setProps({ value }); wrapper.setProps({ value });
}, },
}, },

View File

@ -121,7 +121,7 @@ export default createComponent({
const { value } = this; const { value } = this;
const simple = this.mode !== 'multi'; const simple = this.mode !== 'multi';
const onSelect = value => () => { const onSelect = (value) => () => {
this.select(value, true); this.select(value, true);
}; };
@ -133,7 +133,7 @@ export default createComponent({
> >
{this.prevText || t('prev')} {this.prevText || t('prev')}
</li> </li>
{this.pages.map(page => ( {this.pages.map((page) => (
<li <li
class={[bem('item', { active: page.active }), bem('page'), BORDER]} class={[bem('item', { active: page.active }), bem('page'), BORDER]}
onClick={onSelect(page.number)} onClick={onSelect(page.number)}

View File

@ -84,7 +84,7 @@ export default createComponent({
const defaultIndex = cursor.defaultIndex || +this.defaultIndex; const defaultIndex = cursor.defaultIndex || +this.defaultIndex;
formatted.push({ formatted.push({
values: cursor.children.map(item => item[this.valueKey]), values: cursor.children.map((item) => item[this.valueKey]),
className: cursor.className, className: cursor.className,
defaultIndex, defaultIndex,
}); });
@ -116,7 +116,7 @@ export default createComponent({
this.setColumnValues( this.setColumnValues(
columnIndex, columnIndex,
cursor.children.map(item => item[this.valueKey]) cursor.children.map((item) => item[this.valueKey])
); );
cursor = cursor.children[cursor.defaultIndex || 0]; cursor = cursor.children[cursor.defaultIndex || 0];
@ -205,7 +205,7 @@ export default createComponent({
// @exposed-api // @exposed-api
// get values of all columns // get values of all columns
getValues() { getValues() {
return this.children.map(child => child.getValue()); return this.children.map((child) => child.getValue());
}, },
// @exposed-api // @exposed-api
@ -219,7 +219,7 @@ export default createComponent({
// @exposed-api // @exposed-api
// get indexes of all columns // get indexes of all columns
getIndexes() { getIndexes() {
return this.children.map(child => child.currentIndex); return this.children.map((child) => child.currentIndex);
}, },
// @exposed-api // @exposed-api
@ -232,7 +232,7 @@ export default createComponent({
// @exposed-api // @exposed-api
confirm() { confirm() {
this.children.forEach(child => child.stopMomentum()); this.children.forEach((child) => child.stopMomentum());
this.emit('confirm'); this.emit('confirm');
}, },

View File

@ -154,7 +154,7 @@ test('simulation finger swipe again before transitionend', () => {
// mock getComputedStyle // mock getComputedStyle
// see: https://github.com/jsdom/jsdom/issues/2588 // see: https://github.com/jsdom/jsdom/issues/2588
const originGetComputedStyle = window.getComputedStyle; const originGetComputedStyle = window.getComputedStyle;
window.getComputedStyle = ele => { window.getComputedStyle = (ele) => {
const style = originGetComputedStyle(ele); const style = originGetComputedStyle(ele);
return { return {
@ -188,10 +188,7 @@ test('click column item', () => {
}, },
}); });
wrapper wrapper.findAll('.van-picker-column__item').at(3).trigger('click');
.findAll('.van-picker-column__item')
.at(3)
.trigger('click');
expect(wrapper.emitted('change')[0][1]).toEqual(columns[1]); expect(wrapper.emitted('change')[0][1]).toEqual(columns[1]);
}); });

View File

@ -36,7 +36,8 @@ export default createComponent({
}, },
beforeCreate() { beforeCreate() {
const createEmitter = eventName => event => this.$emit(eventName, event); const createEmitter = (eventName) => (event) =>
this.$emit(eventName, event);
this.onClick = createEmitter('click'); this.onClick = createEmitter('click');
this.onOpened = createEmitter('opened'); this.onOpened = createEmitter('opened');

View File

@ -14,7 +14,7 @@ export default createComponent({
percentage: { percentage: {
type: [Number, String], type: [Number, String],
required: true, required: true,
validator: value => value >= 0 && value <= 100, validator: (value) => value >= 0 && value <= 100,
}, },
showPivot: { showPivot: {
type: Boolean, type: Boolean,

View File

@ -57,7 +57,7 @@ export default {
customCount: '自定义数量', customCount: '自定义数量',
readonly: '只读状态', readonly: '只读状态',
changeEvent: '监听 change 事件', changeEvent: '监听 change 事件',
toastContent: value => `当前值:${value}`, toastContent: (value) => `当前值:${value}`,
}, },
'en-US': { 'en-US': {
halfStar: 'Half Star', halfStar: 'Half Star',
@ -67,7 +67,7 @@ export default {
customCount: 'Custom Count', customCount: 'Custom Count',
readonly: 'Readonly', readonly: 'Readonly',
changeEvent: 'Change Event', changeEvent: 'Change Event',
toastContent: value => `current value${value}`, toastContent: (value) => `current value${value}`,
}, },
}, },

View File

@ -96,7 +96,9 @@ export default createComponent({
this.touchStart(event); this.touchStart(event);
const rects = this.$refs.items.map(item => item.getBoundingClientRect()); const rects = this.$refs.items.map((item) =>
item.getBoundingClientRect()
);
const ranges = []; const ranges = [];
rects.forEach((rect, index) => { rects.forEach((rect, index) => {

View File

@ -17,7 +17,7 @@ test('change event', () => {
const wrapper = mount(Rate, { const wrapper = mount(Rate, {
listeners: { listeners: {
input: value => { input: (value) => {
onInput(value); onInput(value);
wrapper.setProps({ value }); wrapper.setProps({ value });
}, },

View File

@ -37,10 +37,7 @@ test('v-model', () => {
}, },
}); });
wrapper wrapper.findAll('.van-sidebar-item').at(1).trigger('click');
.findAll('.van-sidebar-item')
.at(1)
.trigger('click');
expect(wrapper.vm.active).toEqual(1); expect(wrapper.vm.active).toEqual(1);
}); });
@ -59,10 +56,7 @@ test('disabled prop', () => {
}, },
}); });
wrapper wrapper.findAll('.van-sidebar-item').at(1).trigger('click');
.findAll('.van-sidebar-item')
.at(1)
.trigger('click');
expect(wrapper.vm.active).toEqual(0); expect(wrapper.vm.active).toEqual(0);
}); });

View File

@ -171,7 +171,9 @@ export default createComponent({
} }
// 属性未全选 // 属性未全选
if ( if (
this.propList.some(it => (this.selectedProp[it.k_id] || []).length < 1) this.propList.some(
(it) => (this.selectedProp[it.k_id] || []).length < 1
)
) { ) {
return false; return false;
} }
@ -258,12 +260,12 @@ export default createComponent({
const imageList = [this.goods.picture]; const imageList = [this.goods.picture];
if (this.skuTree.length > 0) { if (this.skuTree.length > 0) {
this.skuTree.forEach(treeItem => { this.skuTree.forEach((treeItem) => {
if (!treeItem.v) { if (!treeItem.v) {
return; return;
} }
treeItem.v.forEach(vItem => { treeItem.v.forEach((vItem) => {
const img = vItem.previewImgUrl || vItem.imgUrl || vItem.img_url; const img = vItem.previewImgUrl || vItem.imgUrl || vItem.img_url;
if (img) { if (img) {
imageList.push(img); imageList.push(img);
@ -306,15 +308,17 @@ export default createComponent({
selectedText() { selectedText() {
if (this.selectedSkuComb) { if (this.selectedSkuComb) {
const values = this.selectedSkuValues.concat(this.selectedPropValues); const values = this.selectedSkuValues.concat(this.selectedPropValues);
return `${t('selected')} ${values.map(item => item.name).join('')}`; return `${t('selected')} ${values.map((item) => item.name).join('')}`;
} }
const unselectedSku = this.skuTree const unselectedSku = this.skuTree
.filter(item => this.selectedSku[item.k_s] === UNSELECTED_SKU_VALUE_ID) .filter(
.map(item => item.k); (item) => this.selectedSku[item.k_s] === UNSELECTED_SKU_VALUE_ID
)
.map((item) => item.k);
const unselectedProp = this.propList const unselectedProp = this.propList
.filter(item => (this.selectedProp[item.k_id] || []).length < 1) .filter((item) => (this.selectedProp[item.k_id] || []).length < 1)
.map(item => item.k); .map((item) => item.k);
return `${t('select')} ${unselectedSku return `${t('select')} ${unselectedSku
.concat(unselectedProp) .concat(unselectedProp)
@ -363,13 +367,13 @@ export default createComponent({
this.selectedSku = {}; this.selectedSku = {};
// 重置 selectedSku // 重置 selectedSku
this.skuTree.forEach(item => { this.skuTree.forEach((item) => {
this.selectedSku[item.k_s] = this.selectedSku[item.k_s] =
this.initialSku[item.k_s] || UNSELECTED_SKU_VALUE_ID; this.initialSku[item.k_s] || UNSELECTED_SKU_VALUE_ID;
}); });
// 只有一个 sku 规格值时默认选中 // 只有一个 sku 规格值时默认选中
this.skuTree.forEach(item => { this.skuTree.forEach((item) => {
const key = item.k_s; const key = item.k_s;
const valueId = item.v[0].id; const valueId = item.v[0].id;
if ( if (
@ -396,7 +400,7 @@ export default createComponent({
this.selectedProp = {}; this.selectedProp = {};
const { selectedProp = {} } = this.initialSku; const { selectedProp = {} } = this.initialSku;
// 只有一个属性值时,默认选中,且选中外部传入信息 // 只有一个属性值时,默认选中,且选中外部传入信息
this.propList.forEach(item => { this.propList.forEach((item) => {
if (item.v && item.v.length === 1) { if (item.v && item.v.length === 1) {
this.selectedProp[item.k_id] = [item.v[0].id]; this.selectedProp[item.k_id] = [item.v[0].id];
} else if (selectedProp[item.k_id]) { } else if (selectedProp[item.k_id]) {
@ -493,7 +497,7 @@ export default createComponent({
onPreviewImage(indexImage) { onPreviewImage(indexImage) {
const { previewOnClickImage } = this; const { previewOnClickImage } = this;
const index = this.imageList.findIndex(image => image === indexImage); const index = this.imageList.findIndex((image) => image === indexImage);
const params = { const params = {
index, index,
@ -615,7 +619,7 @@ export default createComponent({
selectedSku, selectedSku,
selectedSkuComb, selectedSkuComb,
}; };
const slots = name => this.slots(name, slotsProps); const slots = (name) => this.slots(name, slotsProps);
const Header = slots('sku-header') || ( const Header = slots('sku-header') || (
<SkuHeader <SkuHeader
@ -658,9 +662,9 @@ export default createComponent({
slots('sku-group') || slots('sku-group') ||
(this.hasSkuOrAttr && ( (this.hasSkuOrAttr && (
<div class={this.skuGroupClass}> <div class={this.skuGroupClass}>
{this.skuTree.map(skuTreeItem => ( {this.skuTree.map((skuTreeItem) => (
<SkuRow skuRow={skuTreeItem}> <SkuRow skuRow={skuTreeItem}>
{skuTreeItem.v.map(skuValue => ( {skuTreeItem.v.map((skuValue) => (
<SkuRowItem <SkuRowItem
skuList={sku.list} skuList={sku.list}
skuValue={skuValue} skuValue={skuValue}
@ -671,9 +675,9 @@ export default createComponent({
))} ))}
</SkuRow> </SkuRow>
))} ))}
{this.propList.map(skuTreeItem => ( {this.propList.map((skuTreeItem) => (
<SkuRow skuRow={skuTreeItem}> <SkuRow skuRow={skuTreeItem}>
{skuTreeItem.v.map(skuValue => ( {skuTreeItem.v.map((skuValue) => (
<SkuRowPropItem <SkuRowPropItem
skuValue={skuValue} skuValue={skuValue}
skuKeyStr={skuTreeItem.k_id + ''} skuKeyStr={skuTreeItem.k_id + ''}
@ -701,7 +705,7 @@ export default createComponent({
disableStepperInput={this.disableStepperInput} disableStepperInput={this.disableStepperInput}
customStepperConfig={this.customStepperConfig} customStepperConfig={this.customStepperConfig}
hideQuotaText={this.hideQuotaText} hideQuotaText={this.hideQuotaText}
onChange={event => { onChange={(event) => {
this.$emit('stepper-change', event); this.$emit('stepper-change', event);
}} }}
/> />

View File

@ -27,11 +27,12 @@ function getSkuImg(
): string | undefined { ): string | undefined {
let img; let img;
sku.tree.some(item => { sku.tree.some((item) => {
const id = selectedSku[item.k_s]; const id = selectedSku[item.k_s];
if (id && item.v) { if (id && item.v) {
const matchedSku = item.v.filter(skuValue => skuValue.id === id)[0] || {}; const matchedSku =
item.v.filter((skuValue) => skuValue.id === id)[0] || {};
img = matchedSku.previewImgUrl || matchedSku.imgUrl || matchedSku.img_url; img = matchedSku.previewImgUrl || matchedSku.imgUrl || matchedSku.img_url;
return img; return img;
} }

View File

@ -32,7 +32,7 @@ export default createComponent({
this.paddingImg = file.content; this.paddingImg = file.content;
this.uploadFail = false; this.uploadFail = false;
this.uploadImg(file.file, file.content) this.uploadImg(file.file, file.content)
.then(img => { .then((img) => {
this.$emit('input', img); this.$emit('input', img);
this.$nextTick(() => { this.$nextTick(() => {
this.paddingImg = ''; this.paddingImg = '';

View File

@ -37,7 +37,7 @@ export default createComponent({
resetMessageValues(messages) { resetMessageValues(messages) {
const { messageConfig } = this; const { messageConfig } = this;
const { initialMessages = {} } = messageConfig; const { initialMessages = {} } = messageConfig;
return (messages || []).map(message => ({ return (messages || []).map((message) => ({
value: initialMessages[message.name] || '', value: initialMessages[message.name] || '',
})); }));
}, },

View File

@ -180,8 +180,8 @@ export default {
customSkuValidator: () => '请选择xxx', customSkuValidator: () => '请选择xxx',
customStepperConfig: { customStepperConfig: {
quotaText: '单次限购100件', quotaText: '单次限购100件',
stockFormatter: stock => `剩余${stock}`, stockFormatter: (stock) => `剩余${stock}`,
handleOverLimit: data => { handleOverLimit: (data) => {
const { action, limitType, quota, startSaleNum = 1 } = data; const { action, limitType, quota, startSaleNum = 1 } = data;
if (action === 'minus') { if (action === 'minus') {
@ -202,7 +202,7 @@ export default {
留言1: '商品留言', 留言1: '商品留言',
}, },
uploadImg: (file, img) => uploadImg: (file, img) =>
new Promise(resolve => { new Promise((resolve) => {
setTimeout(() => resolve(img), 1000); setTimeout(() => resolve(img), 1000);
}), }),
uploadMaxSize: 3, uploadMaxSize: 3,

View File

@ -34,19 +34,19 @@ import { UNSELECTED_SKU_VALUE_ID } from '../constants';
... ...
} }
*/ */
export const normalizeSkuTree = skuTree => { export const normalizeSkuTree = (skuTree) => {
const normalizedTree = {}; const normalizedTree = {};
skuTree.forEach(treeItem => { skuTree.forEach((treeItem) => {
normalizedTree[treeItem.k_s] = treeItem.v; normalizedTree[treeItem.k_s] = treeItem.v;
}); });
return normalizedTree; return normalizedTree;
}; };
export const normalizePropList = propList => { export const normalizePropList = (propList) => {
const normalizedProp = {}; const normalizedProp = {};
propList.forEach(item => { propList.forEach((item) => {
const itemObj = {}; const itemObj = {};
item.v.forEach(it => { item.v.forEach((it) => {
itemObj[it.id] = it; itemObj[it.id] = it;
}); });
normalizedProp[item.k_id] = itemObj; normalizedProp[item.k_id] = itemObj;
@ -58,16 +58,16 @@ export const normalizePropList = propList => {
export const isAllSelected = (skuTree, selectedSku) => { export const isAllSelected = (skuTree, selectedSku) => {
// 筛选selectedSku对象中key值不为空的值 // 筛选selectedSku对象中key值不为空的值
const selected = Object.keys(selectedSku).filter( const selected = Object.keys(selectedSku).filter(
skuKeyStr => selectedSku[skuKeyStr] !== UNSELECTED_SKU_VALUE_ID (skuKeyStr) => selectedSku[skuKeyStr] !== UNSELECTED_SKU_VALUE_ID
); );
return skuTree.length === selected.length; return skuTree.length === selected.length;
}; };
// 根据已选择的 sku 获取 skuComb // 根据已选择的 sku 获取 skuComb
export const getSkuComb = (skuList, selectedSku) => { export const getSkuComb = (skuList, selectedSku) => {
const skuComb = skuList.filter(item => const skuComb = skuList.filter((item) =>
Object.keys(selectedSku).every( Object.keys(selectedSku).every(
skuKeyStr => String(item[skuKeyStr]) === String(selectedSku[skuKeyStr]) (skuKeyStr) => String(item[skuKeyStr]) === String(selectedSku[skuKeyStr])
) )
); );
return skuComb[0]; return skuComb[0];
@ -81,7 +81,7 @@ export const getSelectedSkuValues = (skuTree, selectedSku) => {
const skuValueId = selectedSku[skuKeyStr]; const skuValueId = selectedSku[skuKeyStr];
if (skuValueId !== UNSELECTED_SKU_VALUE_ID) { if (skuValueId !== UNSELECTED_SKU_VALUE_ID) {
const skuValue = skuValues.filter(value => value.id === skuValueId)[0]; const skuValue = skuValues.filter((value) => value.id === skuValueId)[0];
skuValue && selectedValues.push(skuValue); skuValue && selectedValues.push(skuValue);
} }
return selectedValues; return selectedValues;
@ -100,12 +100,12 @@ export const isSkuChoosable = (skuList, selectedSku, skuToChoose) => {
// 再判断剩余sku是否全部不可选若不可选则当前sku不可选中 // 再判断剩余sku是否全部不可选若不可选则当前sku不可选中
const skusToCheck = Object.keys(matchedSku).filter( const skusToCheck = Object.keys(matchedSku).filter(
skuKey => matchedSku[skuKey] !== UNSELECTED_SKU_VALUE_ID (skuKey) => matchedSku[skuKey] !== UNSELECTED_SKU_VALUE_ID
); );
const filteredSku = skuList.filter(sku => const filteredSku = skuList.filter((sku) =>
skusToCheck.every( skusToCheck.every(
skuKey => String(matchedSku[skuKey]) === String(sku[skuKey]) (skuKey) => String(matchedSku[skuKey]) === String(sku[skuKey])
) )
); );
@ -119,7 +119,7 @@ export const isSkuChoosable = (skuList, selectedSku, skuToChoose) => {
export const getSelectedPropValues = (propList, selectedProp) => { export const getSelectedPropValues = (propList, selectedProp) => {
const normalizeProp = normalizePropList(propList); const normalizeProp = normalizePropList(propList);
return Object.keys(selectedProp).reduce((acc, cur) => { return Object.keys(selectedProp).reduce((acc, cur) => {
selectedProp[cur].forEach(it => { selectedProp[cur].forEach((it) => {
acc.push({ acc.push({
...normalizeProp[cur][it], ...normalizeProp[cur][it],
}); });
@ -130,10 +130,10 @@ export const getSelectedPropValues = (propList, selectedProp) => {
export const getSelectedProperties = (propList, selectedProp) => { export const getSelectedProperties = (propList, selectedProp) => {
const list = []; const list = [];
(propList || []).forEach(prop => { (propList || []).forEach((prop) => {
if (selectedProp[prop.k_id] && selectedProp[prop.k_id].length > 0) { if (selectedProp[prop.k_id] && selectedProp[prop.k_id].length > 0) {
const v = []; const v = [];
prop.v.forEach(it => { prop.v.forEach((it) => {
if (selectedProp[prop.k_id].indexOf(it.id) > -1) { if (selectedProp[prop.k_id].indexOf(it.id) > -1) {
v.push({ ...it }); v.push({ ...it });
} }

View File

@ -25,7 +25,7 @@ test('drag button', () => {
}, },
}); });
wrapper.vm.$on('input', value => { wrapper.vm.$on('input', (value) => {
wrapper.setProps({ value }); wrapper.setProps({ value });
}); });
@ -56,7 +56,7 @@ test('click bar', () => {
}, },
}); });
wrapper.vm.$on('input', value => { wrapper.vm.$on('input', (value) => {
wrapper.setProps({ value }); wrapper.setProps({ value });
}); });
@ -80,7 +80,7 @@ test('drag button vertical', () => {
}, },
}); });
wrapper.vm.$on('input', value => { wrapper.vm.$on('input', (value) => {
wrapper.setProps({ value }); wrapper.setProps({ value });
}); });
@ -101,7 +101,7 @@ test('click vertical', () => {
}, },
}); });
wrapper.vm.$on('input', value => { wrapper.vm.$on('input', (value) => {
wrapper.setProps({ value }); wrapper.setProps({ value });
}); });
@ -151,7 +151,7 @@ test('should not emit change event when value not changed', () => {
expect(wrapper.emitted('change').length).toEqual(1); expect(wrapper.emitted('change').length).toEqual(1);
}); });
test('should format initial value', done => { test('should format initial value', (done) => {
mount(Slider, { mount(Slider, {
propsData: { propsData: {
value: null, value: null,

View File

@ -261,7 +261,7 @@ export default createComponent({
}, },
render() { render() {
const createListeners = type => ({ const createListeners = (type) => ({
on: { on: {
click: () => { click: () => {
this.type = type; this.type = type;

View File

@ -172,7 +172,7 @@ test('stepper blur', () => {
}, },
}); });
wrapper.vm.$on('input', value => { wrapper.vm.$on('input', (value) => {
wrapper.setProps({ value }); wrapper.setProps({ value });
}); });

View File

@ -43,10 +43,7 @@ test('click-step event', () => {
wrapper.find('.van-step__title').trigger('click'); wrapper.find('.van-step__title').trigger('click');
expect(onClickStep).toHaveBeenCalledWith(0); expect(onClickStep).toHaveBeenCalledWith(0);
wrapper wrapper.findAll('.van-step__circle-container').at(2).trigger('click');
.findAll('.van-step__circle-container')
.at(2)
.trigger('click');
expect(onClickStep).toHaveBeenCalledTimes(2); expect(onClickStep).toHaveBeenCalledTimes(2);
expect(onClickStep).toHaveBeenLastCalledWith(2); expect(onClickStep).toHaveBeenLastCalledWith(2);
}); });

View File

@ -7,7 +7,7 @@ const [createComponent, bem] = createNamespace('sticky');
export default createComponent({ export default createComponent({
mixins: [ mixins: [
BindEventMixin(function(bind, isBind) { BindEventMixin(function (bind, isBind) {
if (!this.scroller) { if (!this.scroller) {
this.scroller = getScroller(this.$el); this.scroller = getScroller(this.$el);
} }
@ -67,7 +67,7 @@ export default createComponent({
// compatibility: https://caniuse.com/#feat=intersectionobserver // compatibility: https://caniuse.com/#feat=intersectionobserver
if (!isServer && window.IntersectionObserver) { if (!isServer && window.IntersectionObserver) {
this.observer = new IntersectionObserver( this.observer = new IntersectionObserver(
entries => { (entries) => {
// trigger scroll when visibility changed // trigger scroll when visibility changed
if (entries[0].intersectionRatio > 0) { if (entries[0].intersectionRatio > 0) {
this.onScroll(); this.onScroll();

View File

@ -186,7 +186,7 @@ export default createComponent({
}, },
getClickHandler(position, stop) { getClickHandler(position, stop) {
return event => { return (event) => {
if (stop) { if (stop) {
event.stopPropagation(); event.stopPropagation();
} }

View File

@ -115,7 +115,7 @@ test('before-close prop', () => {
expect(wrapper.vm.offset).toEqual(0); expect(wrapper.vm.offset).toEqual(0);
}); });
test('name prop', done => { test('name prop', (done) => {
const wrapper = mount(SwipeCell, { const wrapper = mount(SwipeCell, {
...defaultProps, ...defaultProps,
propsData: { propsData: {

View File

@ -16,7 +16,7 @@ export default createComponent({
mixins: [ mixins: [
TouchMixin, TouchMixin,
ParentMixin('vanSwipe'), ParentMixin('vanSwipe'),
BindEventMixin(function(bind, isBind) { BindEventMixin(function (bind, isBind) {
bind(window, 'resize', this.resize, true); bind(window, 'resize', this.resize, true);
bind(window, 'visibilitychange', this.onVisibilityChange); bind(window, 'visibilitychange', this.onVisibilityChange);
@ -175,7 +175,7 @@ export default createComponent({
this.swiping = true; this.swiping = true;
this.active = active; this.active = active;
this.offset = this.getTargetOffset(active); this.offset = this.getTargetOffset(active);
this.children.forEach(swipe => { this.children.forEach((swipe) => {
swipe.offset = 0; swipe.offset = 0;
}); });
this.autoPlay(); this.autoPlay();

View File

@ -75,7 +75,7 @@ test('route mode match by name', async () => {
expect(wrapper).toMatchSnapshot(); expect(wrapper).toMatchSnapshot();
}); });
test('router NavigationDuplicated', async done => { test('router NavigationDuplicated', async (done) => {
expect(async () => { expect(async () => {
const router = new VueRouter(); const router = new VueRouter();
const wrapper = mount({ const wrapper = mount({
@ -157,10 +157,7 @@ test('name prop', () => {
}, },
}); });
wrapper wrapper.findAll('.van-tabbar-item').at(1).trigger('click');
.findAll('.van-tabbar-item')
.at(1)
.trigger('click');
expect(onChange).toHaveBeenCalledWith('b'); expect(onChange).toHaveBeenCalledWith('b');
}); });

View File

@ -27,7 +27,7 @@ const [createComponent, bem] = createNamespace('tabs');
export default createComponent({ export default createComponent({
mixins: [ mixins: [
ParentMixin('vanTabs'), ParentMixin('vanTabs'),
BindEventMixin(function(bind) { BindEventMixin(function (bind) {
if (!this.scroller) { if (!this.scroller) {
this.scroller = getScroller(this.$el); this.scroller = getScroller(this.$el);
} }
@ -231,7 +231,7 @@ export default createComponent({
// correct the index of active tab // correct the index of active tab
setCurrentIndexByName(name) { setCurrentIndexByName(name) {
const matched = this.children.filter(tab => tab.computedName === name); const matched = this.children.filter((tab) => tab.computedName === name);
const defaultIndex = (this.children[0] || {}).index || 0; const defaultIndex = (this.children[0] || {}).index || 0;
this.setCurrentIndex(matched.length ? matched[0].index : defaultIndex); this.setCurrentIndex(matched.length ? matched[0].index : defaultIndex);
}, },

View File

@ -69,7 +69,7 @@ export default {
text3: '失败文案', text3: '失败文案',
customIcon: '自定义图标', customIcon: '自定义图标',
customImage: '展示图片', customImage: '展示图片',
text4: second => `倒计时 ${second}`, text4: (second) => `倒计时 ${second}`,
longTextButton: '长文字提示', longTextButton: '长文字提示',
updateMessage: '动态更新提示', updateMessage: '动态更新提示',
loadingType: '自定义加载图标', loadingType: '自定义加载图标',
@ -87,7 +87,7 @@ export default {
text3: 'Fail', text3: 'Fail',
customIcon: 'Custom Icon', customIcon: 'Custom Icon',
customImage: 'Custom Image', customImage: 'Custom Image',
text4: second => `${second} seconds`, text4: (second) => `${second} seconds`,
longTextButton: 'Long Text', longTextButton: 'Long Text',
updateMessage: 'Update Message', updateMessage: 'Update Message',
loadingType: 'Loading Type', loadingType: 'Loading Type',

View File

@ -54,7 +54,7 @@ function createInstance() {
el: document.createElement('div'), el: document.createElement('div'),
}); });
toast.$on('input', value => { toast.$on('input', (value) => {
toast.value = value; toast.value = value;
}); });
@ -99,7 +99,7 @@ function Toast(options = {}) {
if (multiple && !isServer) { if (multiple && !isServer) {
toast.$on('closed', () => { toast.$on('closed', () => {
clearTimeout(toast.timer); clearTimeout(toast.timer);
queue = queue.filter(item => item !== toast); queue = queue.filter((item) => item !== toast);
removeNode(toast.$el); removeNode(toast.$el);
toast.$destroy(); toast.$destroy();
@ -119,20 +119,20 @@ function Toast(options = {}) {
return toast; return toast;
} }
const createMethod = type => options => const createMethod = (type) => (options) =>
Toast({ Toast({
type, type,
...parseOptions(options), ...parseOptions(options),
}); });
['loading', 'success', 'fail'].forEach(method => { ['loading', 'success', 'fail'].forEach((method) => {
Toast[method] = createMethod(method); Toast[method] = createMethod(method);
}); });
Toast.clear = all => { Toast.clear = (all) => {
if (queue.length) { if (queue.length) {
if (all) { if (all) {
queue.forEach(toast => { queue.forEach((toast) => {
toast.clear(); toast.clear();
}); });
queue = []; queue = [];
@ -152,7 +152,7 @@ Toast.setDefaultOptions = (type, options) => {
} }
}; };
Toast.resetDefaultOptions = type => { Toast.resetDefaultOptions = (type) => {
if (typeof type === 'string') { if (typeof type === 'string') {
defaultOptionsMap[type] = null; defaultOptionsMap[type] = null;
} else { } else {

View File

@ -61,7 +61,7 @@ function TreeSelect(
: activeId === id; : activeId === id;
} }
const Navs = items.map(item => ( const Navs = items.map((item) => (
<SidebarItem <SidebarItem
dot={item.dot} dot={item.dot}
info={isDef(item.badge) ? item.badge : item.info} info={isDef(item.badge) ? item.badge : item.info}
@ -76,7 +76,7 @@ function TreeSelect(
return slots.content(); return slots.content();
} }
return subItems.map(item => ( return subItems.map((item) => (
<div <div
key={item.id} key={item.id}
class={[ class={[

View File

@ -293,7 +293,7 @@ test('className of nav', () => {
expect(items.at(0).element.classList.contains('my-class')).toBeTruthy(); expect(items.at(0).element.classList.contains('my-class')).toBeTruthy();
}); });
test('should sync value before trigger click-item event', done => { test('should sync value before trigger click-item event', (done) => {
const wrapper = mount({ const wrapper = mount({
template: ` template: `
<van-tree-select <van-tree-select

View File

@ -117,7 +117,7 @@ export default createComponent({
if (isPromise(response)) { if (isPromise(response)) {
response response
.then(data => { .then((data) => {
if (data) { if (data) {
this.readFile(data); this.readFile(data);
} else { } else {
@ -143,8 +143,8 @@ export default createComponent({
files = files.slice(0, maxCount); files = files.slice(0, maxCount);
} }
Promise.all(files.map(file => readFile(file, this.resultType))).then( Promise.all(files.map((file) => readFile(file, this.resultType))).then(
contents => { (contents) => {
const fileList = files.map((file, index) => { const fileList = files.map((file, index) => {
const result = { file, status: '' }; const result = { file, status: '' };
@ -159,7 +159,7 @@ export default createComponent({
} }
); );
} else { } else {
readFile(files, this.resultType).then(content => { readFile(files, this.resultType).then((content) => {
const result = { file: files, status: '' }; const result = { file: files, status: '' };
if (content) { if (content) {
@ -227,8 +227,8 @@ export default createComponent({
return; return;
} }
const imageFiles = this.fileList.filter(item => isImageFile(item)); const imageFiles = this.fileList.filter((item) => isImageFile(item));
const imageContents = imageFiles.map(item => item.content || item.url); const imageContents = imageFiles.map((item) => item.content || item.url);
this.imagePreview = ImagePreview({ this.imagePreview = ImagePreview({
images: imageContents, images: imageContents,
@ -287,7 +287,7 @@ export default createComponent({
<Icon <Icon
name="clear" name="clear"
class={bem('preview-delete')} class={bem('preview-delete')}
onClick={event => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
this.onDelete(item, index); this.onDelete(item, index);
}} }}

View File

@ -1,7 +1,7 @@
import Uploader from '..'; import Uploader from '..';
import { mount, later, triggerDrag } from '../../../test'; import { mount, later, triggerDrag } from '../../../test';
window.File = function() { window.File = function () {
this.size = 10000; this.size = 10000;
}; };
@ -12,8 +12,8 @@ const multiFile = { target: { files: [mockFile, mockFile] } };
const IMAGE = 'https://img.yzcdn.cn/vant/cat.jpeg'; const IMAGE = 'https://img.yzcdn.cn/vant/cat.jpeg';
const PDF = 'https://img.yzcdn.cn/vant/test.pdf'; const PDF = 'https://img.yzcdn.cn/vant/test.pdf';
window.FileReader = function() { window.FileReader = function () {
this.readAsText = function() { this.readAsText = function () {
this.onload && this.onload &&
this.onload({ this.onload({
target: { target: {
@ -37,11 +37,11 @@ test('disabled', () => {
expect(afterRead).toHaveBeenCalledTimes(0); expect(afterRead).toHaveBeenCalledTimes(0);
}); });
test('result-type as text', done => { test('result-type as text', (done) => {
const wrapper = mount(Uploader, { const wrapper = mount(Uploader, {
propsData: { propsData: {
resultType: 'text', resultType: 'text',
afterRead: readFile => { afterRead: (readFile) => {
expect(readFile.content).toEqual(mockFileDataUrl); expect(readFile.content).toEqual(mockFileDataUrl);
done(); done();
}, },
@ -51,11 +51,11 @@ test('result-type as text', done => {
wrapper.vm.onChange(file); wrapper.vm.onChange(file);
}); });
test('result-type as file', done => { test('result-type as file', (done) => {
const wrapper = mount(Uploader, { const wrapper = mount(Uploader, {
propsData: { propsData: {
resultType: 'file', resultType: 'file',
afterRead: readFile => { afterRead: (readFile) => {
expect(readFile.file).toBeTruthy(); expect(readFile.file).toBeTruthy();
expect(readFile.content).toBeFalsy(); expect(readFile.content).toBeFalsy();
done(); done();
@ -66,7 +66,7 @@ test('result-type as file', done => {
wrapper.vm.onChange(file); wrapper.vm.onChange(file);
}); });
test('set input name', done => { test('set input name', (done) => {
const wrapper = mount(Uploader, { const wrapper = mount(Uploader, {
propsData: { propsData: {
name: 'uploader', name: 'uploader',
@ -117,7 +117,7 @@ test('before read return promise and resolve', async () => {
const wrapper = mount(Uploader, { const wrapper = mount(Uploader, {
propsData: { propsData: {
beforeRead: () => beforeRead: () =>
new Promise(resolve => { new Promise((resolve) => {
resolve(file); resolve(file);
}), }),
afterRead, afterRead,
@ -135,7 +135,7 @@ test('before read return promise and resolve no value', async () => {
const wrapper = mount(Uploader, { const wrapper = mount(Uploader, {
propsData: { propsData: {
beforeRead: () => beforeRead: () =>
new Promise(resolve => { new Promise((resolve) => {
resolve(); resolve();
}), }),
afterRead, afterRead,
@ -360,7 +360,7 @@ test('before-delete prop resolved', async () => {
const wrapper = mount(Uploader, { const wrapper = mount(Uploader, {
propsData: { propsData: {
fileList: [{ url: IMAGE }], fileList: [{ url: IMAGE }],
beforeDelete: () => new Promise(resolve => resolve()), beforeDelete: () => new Promise((resolve) => resolve()),
}, },
}); });

View File

@ -9,7 +9,7 @@ export function toArray<T>(item: T | T[]): T[] {
} }
export function readFile(file: File, resultType: ResultType) { export function readFile(file: File, resultType: ResultType) {
return new Promise(resolve => { return new Promise((resolve) => {
if (resultType === 'file') { if (resultType === 'file') {
resolve(); resolve();
return; return;
@ -17,7 +17,7 @@ export function readFile(file: File, resultType: ResultType) {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = event => { reader.onload = (event) => {
resolve((event.target as FileReader).result); resolve((event.target as FileReader).result);
}; };
@ -33,7 +33,7 @@ export function isOversize(
files: File | File[], files: File | File[],
maxSize: number | string maxSize: number | string
): boolean { ): boolean {
return toArray(files).some(file => file.size > maxSize); return toArray(files).some((file) => file.size > maxSize);
} }
export type FileListItem = { export type FileListItem = {

View File

@ -30,7 +30,7 @@ function gen(name: string, mods?: Mods): string {
} }
export function createBEM(name: string) { export function createBEM(name: string) {
return function(el?: Mods, mods?: Mods): Mods { return function (el?: Mods, mods?: Mods): Mods {
if (el && typeof el !== 'string') { if (el && typeof el !== 'string') {
mods = el; mods = el;
el = ''; el = '';

View File

@ -43,7 +43,7 @@ export function unifySlots(context: RenderContext) {
const scopedSlots = context.scopedSlots || context.data.scopedSlots || {}; const scopedSlots = context.scopedSlots || context.data.scopedSlots || {};
const slots = context.slots(); const slots = context.slots();
Object.keys(slots).forEach(key => { Object.keys(slots).forEach((key) => {
if (!scopedSlots[key]) { if (!scopedSlots[key]) {
scopedSlots[key] = () => slots[key]; scopedSlots[key] = () => slots[key];
} }
@ -66,7 +66,7 @@ function transformFunctionComponent(
} }
export function createComponent(name: string) { export function createComponent(name: string) {
return function<Props = DefaultProps, Events = {}, Slots = {}>( return function <Props = DefaultProps, Events = {}, Slots = {}>(
sfc: VantComponentOptions | FunctionComponent sfc: VantComponentOptions | FunctionComponent
): TsxComponent<Props, Events, Slots> { ): TsxComponent<Props, Events, Slots> {
if (isFunction(sfc)) { if (isFunction(sfc)) {

View File

@ -5,7 +5,7 @@ import locale from '../../locale';
export function createI18N(name: string) { export function createI18N(name: string) {
const prefix = camelize(name) + '.'; const prefix = camelize(name) + '.';
return function(path: string, ...args: any[]): string { return function (path: string, ...args: any[]): string {
const messages = locale.messages(); const messages = locale.messages();
const message = get(messages, prefix + path) || get(messages, path); const message = get(messages, prefix + path) || get(messages, path);

View File

@ -19,7 +19,7 @@ function assignKey(to: ObjectIndex, from: ObjectIndex, key: string) {
} }
export function deepAssign(to: ObjectIndex, from: ObjectIndex): ObjectIndex { export function deepAssign(to: ObjectIndex, from: ObjectIndex): ObjectIndex {
Object.keys(from).forEach(key => { Object.keys(from).forEach((key) => {
assignKey(to, from, key); assignKey(to, from, key);
}); });

View File

@ -2,7 +2,7 @@ import { deepAssign } from './deep-assign';
export function deepClone(obj: object): object { export function deepClone(obj: object): object {
if (Array.isArray(obj)) { if (Array.isArray(obj)) {
return obj.map(item => deepClone(item)); return obj.map((item) => deepClone(item));
} }
if (typeof obj === 'object') { if (typeof obj === 'object') {

View File

@ -43,7 +43,7 @@ export function emit(context: Context, eventName: string, ...args: any[]) {
const listeners = context.listeners[eventName]; const listeners = context.listeners[eventName];
if (listeners) { if (listeners) {
if (Array.isArray(listeners)) { if (Array.isArray(listeners)) {
listeners.forEach(listener => { listeners.forEach((listener) => {
listener(...args); listener(...args);
}); });
} else { } else {

View File

@ -27,7 +27,7 @@ export function get(object: any, path: string): any {
const keys = path.split('.'); const keys = path.split('.');
let result = object; let result = object;
keys.forEach(key => { keys.forEach((key) => {
result = isDef(result[key]) ? result[key] : ''; result = isDef(result[key]) ? result[key] : '';
}); });

View File

@ -18,7 +18,7 @@ export function route(router: VueRouter, config: RouteConfig) {
/* istanbul ignore else */ /* istanbul ignore else */
if (promise && promise.catch) { if (promise && promise.catch) {
promise.catch(err => { promise.catch((err) => {
/* istanbul ignore if */ /* istanbul ignore if */
if (err && err.name !== 'NavigationDuplicated') { if (err && err.name !== 'NavigationDuplicated') {
throw err; throw err;

View File

@ -5,7 +5,7 @@ function flattenVNodes(vnodes: VNode[]) {
const result: VNode[] = []; const result: VNode[] = [];
function traverse(vnodes: VNode[]) { function traverse(vnodes: VNode[]) {
vnodes.forEach(vnode => { vnodes.forEach((vnode) => {
result.push(vnode); result.push(vnode);
if (vnode.children) { if (vnode.children) {