VUE

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

Posted by youthred on April 15, 2021

GIF

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

html

1
2
3
4
5
6
<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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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监听里不要用箭头函数,箭头函数支持不好==