vue ui之 iview 事件拦截

用过easyui的,应该清楚easyui组件有很多before事件拦截,有时候会特别重要。

最近在研究vue的ui组件iview虽然功能也不错,感觉还是没有像easyui那样强大,就比如before事件拦截。

不过也想到了解决方案: props传入函数参数,这里以Switch组件为例(颜色标识的为额外添加的代码)

<template>
    <span :class="wrapClasses" @click="toggle">
        <span :class="innerClasses">
            <slot name="open" v-if="currentValue"></slot>
            <slot name="close" v-if="!currentValue"></slot>
        </span>
    </span>
</template>
<script>
    import { oneOf } from '../../utils/assist';
    import Emitter from '../../mixins/emitter';

    const prefixCls = 'ivu-switch';

    export default {
        name: 'Switch',
        mixins: [ Emitter ],
        props: {
            value: {
                type: Boolean,
                default: false
            },
            disabled: {
                type: Boolean,
                default: false
            },
            size: {
                validator (value) {
                    return oneOf(value, ['large', 'small']);
                }
            },
            beforeChange: {
                type: Function
            }
        },
        data () {
            return {
                currentValue: this.value
            };
        },
        computed: {
            wrapClasses () {
                return [
                    `${prefixCls}`,
                    {
                        [`${prefixCls}-checked`]: this.currentValue,
                        [`${prefixCls}-disabled`]: this.disabled,
                        [`${prefixCls}-${this.size}`]: !!this.size
                    }
                ];
            },
            innerClasses () {
                return `${prefixCls}-inner`;
            }
        },
        methods: {
            toggle () {
                if (this.disabled) {
                    return false;
                }
                if(this.beforeChange && (typeof this.beforeChange=='function')) {
                  var status = this.beforeChange.apply(this,[this.currentValue]);
                  if(status == false) return false;
                }
                const checked = !this.currentValue;
                this.currentValue = checked;
                this.$emit('input', checked);
                this.$emit('on-change', checked);
                this.dispatch('FormItem', 'on-form-change', checked);
            }
        },
        watch: {
            value (val) {
                this.currentValue = val;
            }
        }
    };
</script>