简体   繁体   中英

How can I convert my following regular JavaScript code to VueJS?

import request from "request";

var apikey = "?api_key=" + "???";
var region = localStorage.getItem("region").toLowerCase() + "1";
var user = "???";

request({
    url: "https://" + region + ".api.riotgames.com/lol/summoner/v4/summoners/by-name/" + user + apikey,
    json: true,
},  function(error, response, body) {
        if(!error && response.statusCode == 200) {
            var toParse = body;
            var name = toParse.name;
            console.log("Name: " + name);
        }
});

So this is a code for using riots api, and I'd like to convert it into vue js. Any ideas how to do that? :O

You can use Axios:

import axios from 'axios';

const apikey = "?api_key=" + "???";
const region = localStorage.getItem("region").toLowerCase() + "1";
const user = "???";

export function makeRequest()
{
  return axios.get(
    "https://" + 
    region + 
    ".api.riotgames.com/lol/summoner/v4/summoners/by-name/" + 
    user + apikey)
    .then(response =>
    {
      return response.data.name;
    }).catch(error =>
    {
      return null;
    });
}

Perhaps it would be better if you return the Promise received from the Axios rather than the result of it - in this way you can do whatever you want/need with the Promise, eg show some notification when there is an error.

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