话不多说,先看GIF

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

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

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

html

<div >
    <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监听里不要用箭头函数,箭头函数支持不好

相关文章:

  • 2022-12-23
  • 2021-11-07
  • 2022-12-23
  • 2021-07-11
  • 2021-08-08
  • 2022-12-23
  • 2021-10-23
猜你喜欢
  • 2023-04-07
  • 2021-11-14
  • 2022-12-23
  • 2021-07-20
  • 2021-07-26
  • 2022-12-23
相关资源
相似解决方案