Loading

vue动态class+bootstrap实现表单实时验证显示效果

话不多说,先看GIF

GIF

利用vue的监听和动态class绑定

这里模拟检测输入的字符串是否为“admin”

html

<div id="loginFrom" class="form-group has-feedback" :class="checkStatus.hasClass">
    <div>
        <input name="username" type="text" class="form-control" placeholder="username" v-model="formData.username">
        <span class="glyphicon form-control-feedback" :class="checkStatus.iconClass"></span>
    </div>
</div>

vue

new Vue({
    el: '#app',
    data: {
        formData: {
            username: ''
        },

        checkStatus: {
            hasClass: '',
            iconClass: ''
        }
    },
    created: function () {},
    methods: {},
    watch: {
        'formData.username': function (newValue, oldValue) {
            if (newValue.trim() === 'admin') {
                this.checkStatus.hasClass = 'has-success';
                this.checkStatus.iconClass = 'glyphicon-ok'
            } else {
                this.checkStatus.hasClass = 'has-error';
                this.checkStatus.iconClass = 'glyphicon-remove'
            }
            console.log(newValue + ' -- ' + oldValue)
        }
    }
})

注意watch监听里不要用箭头函数,箭头函数支持不好

posted @ 2020-03-08 16:04  mahoshojo  阅读(878)  评论(0编辑  收藏  举报