博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
vue.js js请求加密_使用Vue.js构建一个加密货币比较网站
阅读量:2509 次
发布时间:2019-05-11

本文共 26835 字,大约阅读时间需要 89 分钟。

vue.js js请求加密

is a simple Javascript framework that lets you build dynamic front-end web applications. Lots of people compare it to and .

是一个简单的Javascript框架,可让您构建动态的前端Web应用程序。 许多人将其与和进行比较。

As a back-end developer, and someone not incredibly experienced with frontend web applications, I've found Vue.js a lot simpler to learn, use, and be successful with vs. React and Angular.

作为一个后端开发人员,并且对前端Web应用程序没有丰富的经验,我发现Vue.js相对于React和Angular更加易于学习,使用和成功。

In this article, I'll walk you through the basics of Vue.js, and in the process we'll build a very simple single page application that compares the prices of the top 10 cryptocurrencies. To keep things simple, we'll just be using plain old HTML, CSS, and Javascript for this – nothing fancy required.

在本文中,我将向您介绍Vue.js的基础知识,并在此过程中,我们将构建一个非常简单的单页应用程序,以比较前10种加密货币的价格。 为了简单起见,我们将仅使用普通的旧HTML,CSS和Javascript-不需要花哨的东西。

( )

Vue.js is a framework designed to handle the view layer of your web applications. This means Vue will only handle things related to displaying the user interface on the page.

Vue.js是一个旨在处理Web应用程序视图层的框架。 这意味着Vue将处理与在页面上显示用户界面有关的事情。

Vue uses plain old HTML, and doesn't require you to learn another language (like JSX with React), and can therefore be picked up by web designers and other front-end developers who are familiar with HTML already.

Vue使用简单的旧HTML,并且不需要您学习其他语言(例如带有React的JSX),因此可以被已经熟悉HTML的Web设计师和其他前端开发人员使用。

If you're looking for a simple Javascript framework to help you dynamically display data, you can't really go wrong with Vue:

如果您正在寻找一个简单的Javascript框架来帮助您动态显示数据,那么Vue真的不会出错:

Vue is simple, fast, and well documented.

Vue简单,快速且有据可查。

( )

Let's take a look at a minimal Vue.js web page:

让我们看一个最小的Vue.js网页:

      

This minimal web page will initialize Vue.js fully, and have it manage everything inside of the app div. The el parameter in the Vue constructor tells Vue to bind itself to the element (in this case a div) whose id is app.

这个最小的网页将完全初始化Vue.js,并使其管理app div中的所有内容。 Vue构造函数中的el参数告诉Vue将自身绑定到ID为app的元素(在本例中为div)。

When Vue starts up, it will begin scanning and managing all the code inside this div.

当Vue启动时,它将开始扫描和管理该div中的所有代码。

( )

One of the core things Vue does is manage data. In order to tell Vue what data you want to manage, you need to explicitly declare every bit of data you expect Vue to dynamically manage for you upfront in a special data object, like so:

Vue的核心功能之一就是管理数据。 为了告诉Vue您想要管理什么数据,您需要在特殊的data对象中明确声明您希望Vue为您动态管理的每一位data ,如下所示:

      

{
{ message }}

Hi Screenshot

As you can see in the example above, I'm defining a new data object inside the Vue constructor, and defining my data inside of it. In this case, I'm just telling Vue that I'd like it to manage a message for me.

如您在上面的示例中看到的,我正在Vue构造函数中定义一个新的data对象,并在其中定义我的数据。 在这种情况下,我只是告诉Vue,我希望它为我管理消息。

You'll also notice that my HTML code now contains a variable: {

{ message }}. After Vue starts up, and scans the app div for code, it will start replacing any variables it finds with the related data objects you've defined.

您还将注意到,我HTML代码现在包含一个变量: {

{ message }} 。 Vue启动后,扫描app div中的代码,它将开始用您定义的相关data对象替换找到的所有变量。

If you open the Javascript console in your browser, and attempt to modify the message value like so:

如果在浏览器中打开Javascript控制台,然后尝试修改消息值,如下所示:

app.message = "yo";

You'll notice that the contents of the page will change!

您会注意到页面的内容将会改变!

Yo Screenshot

This happens because Vue is managing that data for you. When the data changes, Vue re-renders the variable on the page.

发生这种情况是因为Vue正在为您管理该数据。 数据更改后,Vue会在页面上重新呈现该变量。

This behavior makes it really easy to build dynamic web applications, since any time you change data in Javascript, the page is re-rendered on your behalf and you don't need to worry about any sort of UI management.

这种行为使构建动态Web应用程序变得非常容易,因为任何时候使用Java脚本更改数据时,页面都将以您的名义重新呈现,并且您无需担心任何类型的UI管理。

( )

In addition to managing pieces of data, Vue also supports writing programming logic in your HTML templates.

除了管理数据之外,Vue还支持在HTML模板中编写编程逻辑。

Vue supports typical if, else if, and else conditionals using the v-if, v-else-if, and v-else syntax.

Vue支持使用v-ifv-else-ifv-else语法的典型if,else if和else条件。

Let's take a look at a simple Vue application that uses an if-else conditional.

让我们看一个使用if-else条件的简单Vue应用程序。

      

{
{ message }}

This is a secret HTML element.

Welcome to the website.

As you can see above, we now have two paragraph tags, each with a different message. If you run this in your browser, you'll see the following:

如您在上面看到的,我们现在有两个段落标签,每个都有不同的消息。 如果在浏览器中运行此程序,则会看到以下内容:

Welcome to the Website Screenshot

Because the secretMessage variable is false, the conditional statement in HTML will fail to execute, and the else statement code will be ran, outputting the HTML element with the welcome message.

因为secretMessage变量为false,所以HTML中的条件语句将无法执行,并且else语句代码将运行,并输出带有欢迎消息HTML元素。

Since we know Vue is dynamic, we can now open the Javascript console, modify the value of secretMessage, and BAM, the page will re-render with the secret message being shown.

由于我们知道Vue是动态的,因此我们现在可以打开Javascript控制台,修改secretMessage和BAM的值,页面将重新呈现,并显示秘密消息。

Secret Message Screenshot

One important thing to note: when using Vue conditionals, the DOM will be modified. In the example above, when we enable the secretMessage flag and show the message, the previously shown paragraph tag will be completely removed from the DOM.

需要注意的重要一件事:使用Vue条件语句时,将修改DOM。 在上面的示例中,当我们启用secretMessage标志并显示消息时,先前显示的段落标签将从DOM中完全删除。

( )

Vue also supports simple loops. Here's a small example application that uses Vue to loop through an array of shopping items, displaying them in an ordered list:

Vue还支持简单循环。 这是一个小示例应用程序,它使用Vue遍历一系列购物商品,并在有序列表中显示它们:

      

Shopping list

  1. {
    { item }}

When this runs in the browser, you'll see that the v-for directive Vue provides will repeat itself, looping over the contents of the shoppingList array:

当它在浏览器中运行时,您会看到Vue提供的v-for指令将重复自身,从而遍历shoppingList数组的内容:

Shopping List Screenshot

If you go modify the shoppingList array in the Javascript console, you'll notice the same behavior as before: Vue will re-render the shopping list for you automatically.

如果您要在Javascript控制台中修改shoppingList数组,则会注意到与以前相同的行为:Vue将自动为您重新呈现购物清单。

( )

The next basic concept we'll cover is two-way data binding. Up until now, you've seen that whatever data you define in Vue will appropriately render when changed. This is really useful, but there's a little bit more we can do.

我们将介绍的下一个基本概念是双向数据绑定。 到目前为止,您已经看到,在Vue中定义的任何数据在更改后都将正确呈现。 这确实很有用,但是我们可以做更多的事情。

In some circumstances, like when accepting user input, you'll also want Vue to manage user controlled data. This is called two way data binding: when both the user (and you) can manage the same pieces of data in your application.

在某些情况下,例如接受用户输入时,您还希望Vue管理用户控制的数据。 这称为双向数据绑定:当用户(和您)都可以在应用程序中管理相同的数据时。

Let's take a look at a simple Vue application that uses two-way data binding:

让我们看一个使用双向数据绑定的简单Vue应用程序:

      

What's your favorite color?

Your favorite color is... {

{ color }}

As you can see if you try this out yourself, when you enter data into the input box, the color variable is changed, and then re-rendered on the page. This is two-way data binding.

如您所见,如果您自己尝试一下,则在将数据输入到输入框中时,将更改color变量,然后在页面上将其重新呈现。 这是双向数据绑定。

Favorite Color Screenshot

If you go into the Javascript console and modify this directly yourself, you'll see it change again.

如果您进入Javascript控制台并直接自己进行修改,则会看到它再次发生变化。

( )

Now that we've covered some of the fundamental Vue.js properties, let's talk about something a little more interesting: Vue methods.

现在,我们已经涵盖了Vue.js的一些基本属性,让我们来讨论一些更有趣的东西:Vue方法。

In addition to managing data, Vue also provides a convenient way to structure your Javascript actions.

除了管理数据之外,Vue还提供了一种方便的方法来构造Javascript 动作

Let's take a look at a very simple example application that uses a method to capitalize the color from the example above when clicked:

让我们看一个非常简单的示例应用程序,该应用程序在单击时使用一种方法将上面示例中的颜色大写:

      

What's your favorite color?

Your favorite color is... {

{ color }}

Capitalize Screenshot

In this example, we define a function in the methods object of Vue, which simply capitalizes the color variable from before. We then use the v-on:click attribute on out input tag to tell Vue that when the button is clicked, it should run that method.

在此示例中,我们在Vue的methods对象中定义了一个函数,该函数仅将之前的color变量大写。 然后,我们使用out输入标签v-on:clickv-on:click属性来告诉Vue,当单击按钮时,它应该运行该方法。

Pretty straight-forward, right?

很简单,对吧?

( )

Now that we've had a chance to look at some basic Vue.js patterns and usage, let's try to build something with our new found knowledge!

现在,我们已经有机会了解一些基本的Vue.js模式和用法,让我们尝试使用新发现的知识来构建一些东西!

I've been using Bitcoin for many years now, and enjoy working with it, so I thought it'd be fun to hack together a little single page app that displays the top 10 cryptocurrencies as well as their price data.

我已经使用比特币很多年了,并且乐于与之合作,所以我认为将一个显示单个页面的小应用程序并显示其前10种加密货币及其价格数据很有趣。

This could be a useful dashboard for someone who's considering purchasing cryptocurrencies for speculative purposes, as it gives you an idea of how these things are valued at any given time.

对于正在考虑出于投机目的购买加密货币的人来说,这可能是一个有用的仪表板,因为它可以使您了解在任何给定时间这些东西的价值。

So… Let's get started!

因此,让我们开始吧!

NOTE: If you'd rather just look at the completed project on Github, you can check it out at .

注意 :如果您只想查看Github上已完成的项目,可以在 。

( )

The first thing we'll do is get our page bootstrapped with some basic HTML, Javascript libraries, etc.

我们要做的第一件事是使用一些基本HTML,Javascript库等引导页面启动。

Because I'm not a web designer (and have poor visual taste!), we'll be using Twitter's library for basic styling. We'll also be using Vue.js, and a few other small helper libraries which will be explained later on:

因为我不是网页设计师(视觉效果很差!),所以我们将使用Twitter的库进行基本样式设置。 我们还将使用Vue.js以及其他一些小的帮助程序库,稍后将对其进行说明:

  • , a simple Vue.js library that provides some useful template filters for displaying text. In this app, I only the filter for helping to display currency values nicely.

    ,一个简单的Vue.js库,提供了一些有用的模板过滤器来显示文本。 在此应用程序中,我仅使用过滤器来帮助更好地显示货币值。
  • , a popular Javascript library for making HTTP requests

    ,一个用于发出HTTP请求的流行Javascript库

All in all, our basic HTML page with all our dependencies included will look like this:

总而言之,包含所有依赖项的基本HTML页面将如下所示:

      
CryptoCompare

Crypto Compare

This website indexes the top 10 cryptocurrencies by market cap (how much the sum of all coins is collectively worth), and gives you an easy way to compare cryptocurrency performance and rank over the last week.

We've got all our dependencies included, we've got a basic HTML page, and we're ready to start doing some real development work.

我们已经包括了所有依赖项,已经有了基本HTML页面,并且我们准备开始进行一些实际的开发工作。

( )

The first thing I like to do after bootstrapping my page is to lay out the elements where they belong. In this case, since we'll be building a ranked list of the top cryptocurrencies, we'll have a very simple design. It's just an HTML table that lists the top cryptocurrencies, and their associated stats.

自举页面后,我想做的第一件事是对元素所属的元素进行布局。 在这种情况下,由于我们将建立顶级加密货币的排名列表,因此我们将有一个非常简单的设计。 这只是一个HTML表格,列出了排名靠前的加密货币及其相关状态。

Here's the modified HTML and CSS, and what it looks like after defining these basic elements:

这是修改后HTML和CSS,以及定义这些基本元素后的外观:

Rank Name Symbol Price (USD) 1H 1D 1W Market Cap (USD)
/* /static/css/style.css */h1 {
text-align: center;}td img {
width: 25px;}.jumbotron p {
font-size: 1.2em;}.jumbotron {
margin-top: 5em; margin-bottom: 5em;}

CryptoCompare Basic Website

We're off to a good start! We've now got our basic website layout done, and we have a good idea of what data we'll need to make this work, etc.

我们有一个良好的开端! 现在,我们已经完成了基本的网站布局,并且对完成这项工作所需的数据有了很好的了解,等等。

( )

In order to build the rest of this app, we need a way to retrieve a list of the top cryptocurrencies, as well as their stats. For this project, I thought it'd be fun to show the following:

为了构建此应用程序的其余部分,我们需要一种方法来检索顶级加密货币及其统计信息的列表。 对于这个项目,我认为显示以下内容会很有趣:

  • The top 10 cryptocurrencies by market cap (the total worth of all coins for the given currency)

    市值排名前十的加密货币(给定货币的所有硬币的总价值)
  • Each currency's name

    每种货币的名称
  • Each currency's symbol (this is how people typically refer to the currencies on trading platforms)

    每种货币的符号(这是人们通常在交易平台上指代货币的方式)
  • The current price of a single coin in each currency, in USD

    单个硬币在每种货币中的当前价格,以美元为单位
  • The percent change in value of the currency over the last hour, day, and week

    最近一小时,一天和一周内货币价值的变化百分比

Luckily for us, there's a great free API service that provides this exact data. It's called . It doesn't require any registration or setup, you can just read through their API documentation, figure out how the API endpoints work, and plug it into whatever you're building.

幸运的是,有一个很棒的免费API服务可以提供此确切数据。 它称为 。 它不需要任何注册或设置,您只需阅读它们的API文档,弄清楚API端点的工作方式,然后将其插入正在构建的任何产品中即可。

We'll need to use the ticker API provided by CoinMarketCap, which will allow us to grab a list of the top 10 cryptocurrencies, and display their stats. Here's what this API call looks like, and what it returns:

我们将需要使用CoinMarketCap提供的股票代码API,这将使我们能够获取排名前10位的加密货币的列表,并显示其统计信息。 以下是此API调用的样子以及返回的结果:

[  {
"id": "bitcoin", "name": "Bitcoin", "symbol": "BTC", "rank": "1", "price_usd": "2747.54", "price_btc": "1.0", "24h_volume_usd": "2242640000.0", "market_cap_usd": "45223373666.0", "available_supply": "16459587.0", "total_supply": "16459587.0", "percent_change_1h": "-2.83", "percent_change_24h": "19.78", "percent_change_7d": "17.2", "last_updated": "1500596647" }, ...]

As you can see above, the resulting JSON is an array of the top 10 cryptocurrencies. Each JSON object in the array represents one currency, and contains all the information we need.

正如您在上面看到的那样,生成的JSON是前10个加密货币的数组。 数组中的每个JSON对象代表一种货币,并包含我们需要的所有信息。

There is one thing we're missing though. To make our table look nice, I'd also like to display the logo of each cryptocurrency next to their name.

但是,我们缺少一件事。 为了使我们的表看起来更好,我还想在每种加密货币的名称旁边显示其徽标。

Unfortunately, the CoinMarketCap API doesn't have any images, so I did a little Google-ing around and found another API we can use to retrieve metadata about tons of different cryptocurrencies, including their logos!

不幸的是,CoinMarketCap API没有任何图像,所以我做了一些Google搜索,发现了另一个API,我们可以使用该API来检索有关大量不同加密货币的元数据,包括其徽标!

The provides us this data. Much like CoinMarketCap, there's no registration required.

向我们提供了这些数据。 就像CoinMarketCap一样,不需要注册。

The API call we'll use to retrieve data about all the cryptocurrencies looks like this:

我们将用于检索有关所有加密货币的数据的API调用如下所示:

$curl https://www.cryptocompare.com/api/data/coinlist{
... "Data": {
"AVT": {
"Id": "138642", "Url": "/coins/avt/overview", "ImageUrl": "/media/1383599/avt.png", "Name": "AVT", "CoinName": "AventCoin", "FullName": "AventCoin (AVT)", "Algorithm": "N/A", "ProofType": "N/A", "FullyPremined": "0", "TotalCoinSupply": "10000000", "PreMinedValue": "N/A", "TotalCoinsFreeFloat": "N/A", "SortOrder": "1266" }, ... }}

With the new data we have from the API call above, we can correlate a cryptocurrency's symbol (for instance BTC, AVI, etc.) with an ImageUrl that shows a picture of that currency.

利用上面API调用中提供的新数据,我们可以将加密货币的符号(例如BTC,AVI等)与显示该货币图片的ImageUrl

Using this new data, plus the data from CoinMarketCap, we now have everything we need!

使用此新数据,再加上来自CoinMarketCap的数据,我们现在拥有了所需的一切!

( )

Now that we know how to grab the data we need, let's start building out our Vue app. To keep things simple, all our Vue code will be placed into the file static/js/app.js.

现在我们知道了如何获取所需数据,让我们开始构建Vue应用程序。 为了简单起见,我们所有的Vue代码都将放置在文件static/js/app.js

The first thing we need to do here is scaffold our Vue app, and tell it what variables we expect it to manage:

我们需要在这里做的第一件事是搭建我们的Vue应用程序的脚手架,并告诉我们我们希望它管理什么变量:

/** * Our Vue.js application. * * This manages the entire front-end website. */// The API we're using for grabbing metadata about each cryptocurrency// (including logo images). The service can be found at:// https://www.cryptocompare.com/api/let CRYPTOCOMPARE_API_URI = "https://www.cryptocompare.com";// The API we're using for grabbing cryptocurrency prices.  The service can be// found at: https://coinmarketcap.com/api/let COINMARKETCAP_API_URI = "https://api.coinmarketcap.com";// The amount of milliseconds (ms) after which we should update our currency// charts.let UPDATE_INTERVAL = 60 * 1000;let app = new Vue({
el: "#app", data: {
coins: [], coinData: {
} }, methods: {
/** * Load up all cryptocurrency data. This data is used to find what logos * each currency has, so we can display things in a friendly way. */ getCoinData: function() {
}, /** * Get the top 10 cryptocurrencies by value. This data is refreshed each 5 * minutes by the backing API service. */ getCoins: function() {
}, /** * Given a cryptocurrency ticket symbol, return the currency's logo * image. */ getCoinImage: function(symbol) {
} }});

The two variables we're going to have Vue manage for us to make this possible are:

我们将让Vue管理以使之成为可能的两个变量是:

  • coins - which will be an array of all the different types of cryptocurrencies (bitcoin, ethereum, etc.), and

    coins -将包含所有不同类型的加密货币(比特币,以太坊等)的数组,以及

  • coinData - which will be an object loaded from the CryptoCompare API service we looked at earlier. Using this we'll be able to cross reference cryptocurrency data to get a logo image. We're also going to define three stub methods that we'll need to implement:

    coinData将是我们从前面看过的CryptoCompare API服务加载的对象。 使用此工具,我们将能够交叉引用加密货币数据以获得徽标图像。 我们还将定义三个需要实现的存根方法:

  • getCoinData - which will retrieve the coin data from CryptoCompare

    getCoinData将从CryptoCompare检索硬币数据

  • getCoins - which will load the coin data from CoinMarketCap

    getCoins从CoinMarketCap加载硬币数据

  • getCoinImage - which takes a currency symbol and returns a link to that currency's logo image

    getCoinImage使用货币符号并返回该货币徽标图像的链接

With these three methods in place, we can now begin writing some software!

有了这三种方法,我们现在可以开始编写一些软件!

( )

Let's start by implementing the getCoins method that will talk to the CoinMarketCap API. We know from before that all we need to do is hit the API and store the resulting array of JSON data in our Vue variable.

让我们从实现与CoinMarketCap API对话的getCoins方法开始。 我们从之前知道,我们需要做的就是点击API并将结果的JSON数据数组存储在我们的Vue变量中。

To make API requests, I like to use the axios Javascript library (mentioned earlier on in this article). It's a very popular library for making HTTP requests in client side Javascript.

为了发出API请求,我喜欢使用axios Javascript库(在本文前面提到)。 这是一个非常流行的库,用于在客户端Javascript中发出HTTP请求。

Since I've already loaded it up for us in the web scaffold, we can use it directly in our Vue code:

由于我已经在Web支架中为我们加载了它,因此我们可以直接在Vue代码中使用它:

getCoins: function() {
let self = this; axios.get(COINMARKETCAP_API_URI + "/v1/ticker/?limit=10") .then((resp) => {
this.coins = resp.data; }) .catch((err) => {
console.error(err); });},

As you can see, we can easily use axios to issue a GET request for us, grab the resulting array of data, and then store it as self.coins (which updates the Vue coins variable). Once that variable change occurs, Vue will re-render any part of our page that's dependent upon it.

如您所见,我们可以轻松地使用axios向我们发出GET请求,获取结果数据数组,然后将其存储为self.coins (更新Vue coins变量)。 发生该变量更改后,Vue将重新渲染页面上依赖它的任何部分。

Next, let's implement our other method: getCoinData, which retrieves metadata about many different types of cryptocurrencies, and will be used to find their logo images:

接下来,让我们实现另一个方法: getCoinData ,该方法检索有关许多不同类型的加密货币的元数据,并将用于查找其徽标图像:

getCoinData: function() {
let self = this; axios.get(CRYPTOCOMPARE_API_URI + "/api/data/coinlist") .then((resp) => {
this.coinData = resp.data.Data; this.getCoins(); }) .catch((err) => {
this.getCoins(); console.error(err); });}

This is another simple API call: we make the request and update the data. One thing we will do here, however, is call the getCoins method as well. We do this because we'll only need to call this method once when the page has loaded (to load up all the currency metadata), but will need to call the getCoins method many times to keep the data up-to-date, and we should only call it once the metadata about all coins has already been loaded.

这是另一个简单的API调用:我们发出请求并更新数据。 但是,我们在这里要做的一件事就是也调用getCoins方法。 我们这样做是因为我们只需要在页面加载后调用此方法一次(以加载所有货币元数据),但是将需要多次调用getCoins方法以使数据保持最新,并且我们应该仅在有关所有硬币的元数据已加载后才调用它。

The last major coin method we need to implement is getCoinImage, which takes in a coin's symbol and returns the full image URL. Here's how we do that:

我们需要实现的最后一个主要硬币方法是getCoinImage ,它接受硬币的符号并返回完整的图像URL。 我们的操作方法如下:

getCoinImage: function(symbol) {
return CRYPTOCOMPARE_API_URI + this.coinData[symbol].ImageUrl;}

This code takes care of the cross-referencing between both API services, and allows us to easily retrieve a cryptocurrency's image.

此代码负责两个API服务之间的交叉引用,并使我们能够轻松检索加密货币的图像。

( )

Now that we've built some of our data-retrieval methods, we need to actually run them. Otherwise: oup app will open, but nothing will happen.

现在我们已经构建了一些数据检索方法,我们需要实际运行它们。 否则:oup应用程序将打开,但是什么也不会发生。

In Vue, we can bind actions to certain events that happen on the page. One of these lifecycle events is called “created”, and we can use this lifecycle hook to run our code once the Vue app has been fully initialized in the browser.

在Vue中,我们可以将动作绑定到页面上发生的某些事件。 这些生命周期事件之一称为“已创建”,一旦在浏览器中完全初始化了Vue应用程序,我们就可以使用该生命周期挂钩来运行代码。

Here's what it looks like:

看起来是这样的:

let app = new Vue({
// ... created: function() {
this.getCoinData(); }});

This is exactly what we need, because once the page is loaded, we'll call our getCoinData method which will retrieve all coin image URls, then we'll call our getCoins method which will load the initial data we need to eventually display on the page.

这正是我们需要的,因为一旦页面加载getCoinData ,我们将调用getCoinData方法,该方法将检索所有硬币图像URls,然后我们将调用getCoins方法,该方法将加载最终需要显示在页面上的初始数据。页。

Finally, we need to ensure that we actually keep the data on the page updating. The CryptoMarketCap API service says that their data is refreshed once every 5 minutes, so as to not be aggressive, we'll be querying their API once per minute to display new results to our users.

最后,我们需要确保我们实际上使页面上的数据保持更新。 CryptoMarketCap API服务表示,他们的数据每5分钟刷新一次,为了不引起攻击,我们将每分钟查询一次他们的API,以向用户显示新结果。

We can do this easily outside of our Vue app using a plain old call to Javascript's setInterval function:

我们可以使用对Javascript的setInterval函数的简单旧调用在Vue应用程序外部轻松完成此操作:

/** * Once the page has been loaded and all of our app stuff is working, we'll * start polling for new cryptocurrency data every minute. * */setInterval(() => {
app.getCoins();}, UPDATE_INTERVAL);

Notice how we're able to run our Vue method outside of our Vue app by calling it off the Vue app object. Vue publicly exports all of your data and methods so they can be used outside Vue.

请注意,通过从Vue应用程序对象中调用它,我们如何能够在Vue应用程序之外运行Vue方法。 Vue公开导出您的所有数据和方法,以便可以在Vue外部使用它们。

( )

Now that we've built the data management side of things, let's hop back into our HTML code and actually display some of this shiny new data for our users.

现在,我们已经构建了数据管理方面的内容,让我们跳回到HTML代码中,并为用户显示一些闪亮的新数据。

Using the same constructs we learned earlier, we're going to loop through the cryptocurrency data, filling out our table:

使用我们之前学习的相同构造,我们将遍历加密货币数据,并填写表:

Rank Name Symbol Price (USD) 1H 1D 1W Market Cap (USD)
{
{ coin.rank }}
{
{ coin.name }}
{
{ coin.symbol }}
{
{ coin.price_usd | currency }}
+{
{ coin.percent_change_1h }}%
+{
{ coin.percent_change_24h }}%
+{
{ coin.percent_change_7d }}%
{
{ coin.market_cap_usd | currency }}

Pretty straightforward, right?

很简单吧?

The only new thing here is the v-bind directive. If you're wondering what that does, it tells Vue to run the getCoinImage function, grab the result, and use that result for the img tag's src attribute (this is how we're able to display the logo to the user).

这里唯一的新东西是v-bind指令。 如果您想知道这样做是什么,它会告诉Vue运行getCoinImage函数,获取结果,并将该结果用于img标签的src属性(这是我们能够向用户显示徽标的方式)。

The final thing we'll want to do now is clean the coloring up a bit:

我们现在要做的最后一件事是清除着色:

  • If the percent change in a currency is positive, we should color it green

    如果某货币的百分比变动为正,则应将其涂成绿色
  • If the percent change in a currency is negative, we should color it red

    如果某货币的百分比变动为负,则应将其涂成红色

This adds a bit more visual flair to the page, and makes it a little easier to eyeball the performance of a currency.

这会在页面上增加一些视觉效果,并使查看货币性能更容易一些。

So, let's quickly build a method and plug it into our HTML:

因此,让我们快速构建一个方法并将其插入我们HTML:

/** * Return a CSS color (either red or green) depending on whether or * not the value passed in is negative or positive. */getColor: (num) => {
return num > 0 ? "color:green;" : "color:red;";}
      {
{ coin.rank }} {
{ coin.name }} {
{ coin.symbol }} {
{ coin.price_usd | currency }} +{
{ coin.percent_change_1h }}% +{
{ coin.percent_change_24h }}% +{
{ coin.percent_change_7d }}% {
{ coin.market_cap_usd | currency }}

With these final changes, load the code up in your browser, and give it a go!

完成这些最终更改后,将代码加载到浏览器中,然后开始吧!

CryptoCompare Final

If you play around with the website a bit, you'll notice that every 60 seconds the data is updated as designed.

如果您稍微浏览一下网站,您会发现每60秒钟就会按设计更新一次数据。

In the event one currency takes over another's ranking, all the items will shift seamlessly on the page (you can play around with this in the Javascript console by modifying app.coins directly if you want).

如果一种货币取代了另一种货币的排名,则所有项目都将在页面上无缝app.coins (您可以在Javascript控制台中通过直接修改app.coins来解决这个问题)。

( )

I hope you had fun learning a bit about Vue, and seeing how to use it to build basic web apps.

我希望您在学习有关Vue的知识方面有所收获,并了解如何使用它来构建基本的Web应用程序。

If you're a web developer looking to organize your front-end logic in a simpler and maintainable way, I strongly recommend you give Vue.js a try.

如果您是一名Web开发人员,希望以一种更简单且可维护的方式来组织前端逻辑,那么我强烈建议您尝试一下Vue.js。

And finally, if you're interested in reading other articles about web development, APIs, and security, you should check out the , and follow on twitter.

最后,如果您有兴趣阅读有关Web开发,API和安全性的其他文章,则应查看 ,并在Twitter上关注 。

翻译自:

vue.js js请求加密

转载地址:http://zzywd.baihongyu.com/

你可能感兴趣的文章
Javascript 高阶函数等
查看>>
【MM系列】在SAP里查看数据的方法
查看>>
C#——winform
查看>>
CSS3 transform制作的漂亮的滚动式导航
查看>>
《小强升职记——时间管理故事书》读书笔记
查看>>
Alpha 冲刺(3/10)
查看>>
Kaldi中的Chain模型
查看>>
spring中的ResourceBundleMessageSource使用和测试示例
查看>>
css规范 - bem
查看>>
SQL 通用数据类型
查看>>
UVALive 6145 Version Controlled IDE(可持久化treap、rope)
查看>>
mysql 将两个有主键的表合并到一起
查看>>
底部导航栏-----FragmentTabHost
查看>>
在linux中安装jdk以及tomcat并shell脚本关闭启动的进程
查看>>
apk,task,android:process与android:sharedUserId的区别
查看>>
MySQL 同主机不同数据库之间的复制
查看>>
iOS菜鸟开发 UIView,UIImageView 的点击事件
查看>>
取得GridView被隐藏列的值方法集合
查看>>
第七章例7-14
查看>>
SQL Server 维护计划实现数据库备份(Step by Step)
查看>>