Vue implementation to verify whether the user name is available

Verify that the username is available

Insert picture description here

Case effect

Insert picture description here

Implementation steps (ideas)

  1. Data binding through v-model
  2. Need to provide prompt information
  3. Need a listener to monitor changes in input information
  4. Need to modify the triggered event

Further adjustment is

  1. Use a listener to monitor user name changes
  2. If the user name changes (call the background interface for verification)
  3. Adjust the prompt information according to the verification result

Code

Basic layout

<div id="app">
        <span>用户名:</span>
        <span>
            <input type="text" v-model.lazy="uname">
        </span>
        <span>
            {
   
   {tip}}
        </span>
    </div>

Realize specific functions through listeners

<script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript">
        /* 侦听器
        采用侦听器监听用户名的变化
        如果用户名发生变化(调用后台接口进行验证)
        根据验证的结果调整提示信息 */
        var vm = new Vue({
    
    
            el: "#app",
            data: {
    
    
                uname: '',
                tip: ''
            },
            methods: {
    
    
                checkName: function (uname) {
    
    
                    // 调用接口,但是可以使用定时任务的方式模拟接口调用
                    var that = this;
                    setTimeout(function () {
    
    
                        // 模拟接口调用
                        if (uname == 'admin') {
    
    
                            that.tip = '用户名已经存在,请更换一个'
                        } else {
    
    
                            that.tip = '用户名可以使用'
                        }
                    }, 1000)
                }
            },
            watch: {
    
    
                uname: function (val) {
    
    
                    // 调用后台接口验证用户名的合法性
                    this.checkName(val);
                    this.tip = '正在验证...'
                }
            },

        });
    </script>

Self-motivation

People need constant encouragement, only constant encouragement can show themselves to the maximum. Encouragement is the motor that people move forward in adversity. As long as you continue to encourage yourself, you can maintain a state of indomitable progress.

Guess you like

Origin blog.csdn.net/weixin_50001396/article/details/112798521