简体   繁体   中英

Vue - real-time fetching of data from REST API

So, I have an input for the user to enter his username. The username is bound to the vue instance via v-model .

I made this function in my controller to check if a username is unique or not (tested and it works):

/**
 * @description
 * GET /api/account/unique/username/:username
 * Checks if new user signing up has a unique username
 */
module.exports.isUsernameUnique = function isUsernameUnique(req, res, next) {
  const username = req.params.username;
  if(!username) {
    return res.status(400).send({ message: 'Username is missing.' });
  }

  personRepository.findPersonByUsername(username, (err, person) => {
    if(person) {
      return res.status(400).send({ message: 'Username has already been taken.' });
    } else {
      res.status(200).send({ unique: true });
    }
  });
};

In my vue script:

data: {
    username: ''
},
methods: {
  isUsernameUnique: function() {
    var self = this;
    var url = 'api/account/unique/username/' + self.username;
    self.$http.get(url)
      .then(function(res){
      }, function(err){
      });
  }
}

If the username typed by the user is not unique, a span below the input should be displayed with an error message almost immediately. How do I accomplish this?

You can add one flag variable in your data() with initial value of false which will get true once the response from api gives result as username is unique.

Please take a look of below code change:

data: {
    username: '',
    isUniqueUserName: false
    },
methods: {
  isUsernameUnique: function() {
    var self = this;
    var url = 'api/account/unique/username/' + self.username;
    self.$http.get(url)
      .then(function(res){
         if(res.unique) this.isUniqueUserName = true;
      }, function(err){
      });
  }
}

In your span add this

<span v-if="!isUniqueUserName ">User Name is Not Unique</span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM