From 144a3fefd3184d0f6263ce9df35c339aadcf14f1 Mon Sep 17 00:00:00 2001 From: neverland Date: Thu, 14 Feb 2019 13:58:07 +0800 Subject: [PATCH] [improvement] Switch: functional (#2736) --- packages/switch/index.js | 64 +++++++++++++++--------------- packages/switch/test/index.spec.js | 37 ++++++++++++++--- 2 files changed, 65 insertions(+), 36 deletions(-) diff --git a/packages/switch/index.js b/packages/switch/index.js index 315cbdae7..f594d288d 100644 --- a/packages/switch/index.js +++ b/packages/switch/index.js @@ -1,41 +1,43 @@ import { use } from '../utils'; import Loading from '../loading'; import { switchProps } from './shared'; +import { emit, inherit } from '../utils/functional'; const [sfc, bem] = use('switch'); -export default sfc({ - props: switchProps, +function Switch(h, props, slots, ctx) { + const { value, loading, disabled, activeValue, inactiveValue } = props; - methods: { - onClick() { - if (!this.disabled && !this.loading) { - const checked = this.value === this.activeValue; - const value = checked ? this.inactiveValue : this.activeValue; - this.$emit('input', value); - this.$emit('change', value); - } + const style = { + fontSize: props.size, + backgroundColor: value ? props.activeColor : props.inactiveColor + }; + + const onClick = event => { + if (!disabled && !loading) { + const newValue = value === activeValue ? inactiveValue : activeValue; + emit(ctx, 'input', newValue); + emit(ctx, 'change', newValue); } - }, + }; - render(h) { - const { value } = this; - const style = { - fontSize: this.size, - backgroundColor: value ? this.activeColor : this.inactiveColor - }; - - return ( -
-
{this.loading && }
+ return ( +
+
+ {loading && }
- ); - } -}); +
+ ); +} + +Switch.props = switchProps; + +export default sfc(Switch); diff --git a/packages/switch/test/index.spec.js b/packages/switch/test/index.spec.js index f164787b3..1b46f6a72 100644 --- a/packages/switch/test/index.spec.js +++ b/packages/switch/test/index.spec.js @@ -2,12 +2,39 @@ import Switch from '..'; import { mount } from '../../../test/utils'; test('emit event', () => { - const wrapper = mount(Switch); + const input = jest.fn(); + const change = jest.fn(); + const wrapper = mount(Switch, { + context: { + on: { + input, + change + } + } + }); wrapper.trigger('click'); wrapper.trigger('click'); - wrapper.setProps({ disabled: true }); - wrapper.trigger('click'); - expect(wrapper.emitted('input')).toEqual([[true], [true]]); - expect(wrapper.emitted('change')).toEqual([[true], [true]]); + expect(input.mock.calls).toEqual([[true], [true]]); + expect(change.mock.calls).toEqual([[true], [true]]); +}); + +test('disabled', () => { + const input = jest.fn(); + const change = jest.fn(); + const wrapper = mount(Switch, { + context: { + on: { + input, + change + } + }, + propsData: { + disabled: true + } + }); + wrapper.trigger('click'); + + expect(input.mock.calls.length).toBeFalsy(); + expect(change.mock.calls.length).toBeFalsy(); });