简体   繁体   English

如何将以下常规 JavaScript 代码转换为 VueJS?

[英]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.所以这是一个使用riots api的代码,我想把它转换成vue js。 Any ideas how to do that?任何想法如何做到这一点? :O :O

You can use Axios:您可以使用 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.如果您返回从 Axios 接收到的 Promise 而不是它的结果,也许会更好 - 这样您就可以对 Promise 执行任何您想要/需要的操作,例如,在出现错误时显示一些通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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