jquery.vue.js_一個Vue.js簡介,面向只了解jQuery的人

jquery.vue.js

by Matt Rothenberg

馬特·羅森伯格(Matt Rothenberg)

一個Vue.js簡介,面向只了解jQuery的人 (A Vue.js introduction for people who know just enough jQuery to get by)

I’ve had a love-hate relationship with JavaScript for years.

我與JavaScript的戀愛關系已經很多年了。

I got to know the language by way of the design and development community’s favorite whipping boy, jQuery. You see, at the time I began learning JavaScript, as a “Designer who codes,” working with jQuery was a magical experience. I could make modals fadeIn and fadeOut. With a third-party library, I could add parallax scrolling to my portfolio with just a single function call. Nearly everything I could have possibly dreamed of was encapsulated in a single, ~100kb file…

我是通過設計和開發社區最喜歡的鞭子jQuery來了解這種語言的。 您會發現,當我開始學習JavaScript時,作為一個“編碼設計師”,使用jQuery是一種神奇的體驗。 我可以使模式fadeIn fadeOut 。 使用第三方庫,我可以僅通過一個函數調用就將視差滾動添加到我的產品組合中。 我可能夢dream以求的幾乎所有內容都封裝在一個?100kb的文件中 ……

And then Angular came out. I had no choice but to redo my entire portfolio with the framework. And then React came out. I had no choice but to redo my entire portfolio with the library. And then Vue.js came out. I had no choice but to redo my entire portfolio with the library… You see where this is going.

然后Angular出來了。 我只好重做我的整個投資組合的框架。 然后React出來了。 我只好重做我的整個投資組合的庫。 然后Vue.js出來了。 我只好重做我的整個投資組合與庫......你看這是怎么回事。

All jokes aside, I have greatly enjoyed honing my JavaScript chops through building things here and there with these different frameworks and libraries. I have read countless articles and tutorials in the process, but none has stuck with me more than Shu Uesugi’s piece, “React.js Introduction For People Who Know Just Enough jQuery To Get By.”

撇開所有笑話,我非常喜歡通過使用這些不同的框架和庫在各處構建事物來磨練我JavaScript技巧。 在此過程中,我閱讀了無數的文章和教程,但是除了Shu Uesugi的文章“ React.js入門,這些人只了解足夠的jQuery才能通過 。

Shu takes readers — who are presumed to have some level of proficiency with JavaScript fundamentals and jQuery — on a journey through the world of React as they build a clone of Twitter’s “compose tweet” component.

Shu使讀者(假定他們對JavaScript基礎和jQuery具有一定程度的熟練程度)在構建Twitter的“ compose tweet”組件的副本時經歷了React的世界。

This conceptual frame was quite helpful to me as someone who learns best by doing. Indeed, any time a new JavaScript library comes out, I find myself going back to the example from this article to test the waters. And so, I would like to borrow this frame as I step you all through my recent experience of learning Vue.

作為一個從中學到東西的人,這個概念框架對我很有幫助。 確實,每當新JavaScript庫問世時,我都會回到本文的示例中來進行測試。 因此,在我逐步學習Vue的最新經歷中,我想借用這個??框架。

Before you begin the steps below, I highly encourage you to read Shu’s article. He does a fantastic job of walking you through the jQuery code you might write in order to implement some of these features. Thus, and so as to mitigate the risk of redundancy, I will focus on showing you the ins-and-outs of Vue.

在您開始以下步驟之前,強烈建議您閱讀Shu的文章。 他出色地完成了帶您完成可能要實現這些功能的jQuery代碼的工作。 因此,為了減輕冗余的風險,我將著重向您展示Vue的來龍去脈。

我們正在建設什么 (What We’re Building)

Most of us tweet (some more prolifically than others). So we are probably familiar with the User Interface component in the screenshot below.

我們大多數人發推文(有些人發的話比其他人發的話)。 因此,我們可能熟悉以下屏幕截圖中的用戶界面組件。

Believe it or not, this UI component is a great example of how Vue (and React, as per Shu) might improve your life as a JavaScript/jQuery developer. The elements of this component that we will focus on building today are:

信不信由你,這個UI組件是Vue(以及Shu所說的React)如何改善您作為JavaScript / jQuery開發人員的生活的一個很好的例子。 我們今天將重點關注的該組件的元素是:

  • The <textarea> where users can enter their tweet

    <textar ea>用戶可以在其中輸入其推文

  • The <button> that is enabled/disabled as a function of how long the tweet is

    啟用/禁用<butt on>的功能取決于推文的持續時間

  • A counter that indicates how many characters (out of 140) remain, and changes color to warn the user of this limit

    一個計數器,指示剩余的字符數(共140個),并更改顏色以警告用戶此限制
  • A camera icon that, when clicked, allows users to attach photos to their tweet

    單擊相機圖標后,用戶可以將照片附加到其推文中
  • A list of photos that have been attached

    已附加的照片列表
  • A button (per each photo) to remove it from the tweet

    一個按鈕(每張照片)可將其從推文中刪除

如果你被困 (If You’re Stuck)

If at any point you come across something that is confusing or poorly explained, don’t hesitate to tweet me at @mattrothenberg. Keep in mind as you read this article: it’s not you, it’s definitely me.

如果您在任何時候遇到令人困惑或難以解釋的事情,請隨時通過@mattrothenberg推特給我。 閱讀本文時請記住:不是您,肯定是我。

Let’s get started.

讓我們開始吧。

我們如何建造它 (How We’re Building It)

Today, we will be using CodePen to build our “Compose Tweet” component. For the uninitiated, CodePen is an online HTML/CSS/JavaScript editor akin to JSBin or JSFiddle. For each step, I’ll embed a CodePen with the relevant code.

今天,我們將使用CodePen構建“ Compose Tweet”組件。 對于初學者,CodePen是類似于JSBin或JSFiddle的在線HTML / CSS / JavaScript編輯器。 對于每一步,我都會在CodePen中嵌入相關代碼。

步驟1:搭建項目 (Step 1: Scaffold The Project)

The first thing we need to do, before writing any JavaScript, is to write the markup for our “Compose Tweet” component. Today we will be using Tachyons for almost all of our stylistic needs (so that we don’t have to write extraneous CSS, and can focus on the markup and JavaScript).

在編寫任何JavaScript之前,我們要做的第一件事是為“ Compose Tweet”組件編寫標記。 今天,我們將使用Tachyons滿足幾乎所有的樣式需求(這樣我們就不必編寫多余CSS,而可以專注于標記和JavaScript)。

I am running with the assumption that you are pretty CSS savvy, so I will not spend time walking you through the Tachyons approach to styling (tl;dr so style, much classes, very functional).

我假設您非常精通CSS,所以我不會花時間介紹Tachyons樣式(tl這樣的樣式,很多類,非常實用)。

In this CodePen I have also gone ahead and pulled in Vue via CDN. Indeed, one of the main selling points of Vue is the simplicity by which it can be integrated into a new or existing codebase.

在此CodePen中,我還繼續前進并通過CDN引入了Vue。 確實,Vue的主要賣點之一就是可以將其集成到新的或現有代碼庫中的簡便性。

With everything in place, let us get started on some feature work.

一切就緒后,讓我們開始進行一些功能工作。

步驟2:實施第一個功能-最初應禁用Tweet按鈕 (Step 2: Implement the First Feature — Tweet Button Should Initially Be Disabled)

Feature Description: Disable the blue Tweet button until a user has entered at least one character in the textarea .

功能描述 :禁用藍色的Tweet按鈕,直到用戶在textarea輸入了至少一個字符為止。

First things first, let us set up our Vue instance. As mentioned above, Vue has won the hearts and minds of Developers by its simplicity of installation and ease of use. We can construct a Vue instance with the following code.

首先,讓我們設置Vue實例。 如上所述,Vue以其安裝簡便和易用性贏得了開發人員的青睞。 我們可以使用以下代碼構造Vue實例。

new Vue({  el: '#twitterVue',  data: {    tweet: ''  },  computed: {    tweetIsEmpty: function() {      return this.tweet.length === 0;    }  }})

Let me explain what is going on here —

讓我解釋一下這是怎么回事-

  • el refers to the DOM element to which we are attaching our Vue instance. This should feel similar to instantiating a jQuery plugin by passing in a given selector, be it a class name or ID.

    el表示我們要將Vue實例附加到的DOM元素。 這應該類似于通過傳入給定的選擇器實例化jQuery插件,無論是類名還是ID。

  • data is an object that describe’s our instance’s data model, or state. We can access the attributes specified within this model both in our HTML — via a special curly brace syntax {{tweet}}— and within the instance itself (hint, look at the body of the tweetIsEmpty function)

    data是描述我們實例的數據模型或狀態的對象。 我們可以在HTML中(通過特殊的花括號語法{{tweet}} )和實例本身(在提示中,查看tweetIsEmpty函數的tweetIsEmpty )訪問在模型中指定的屬性。

  • computed is an object that describes, as you might guess, computed properties based on our data model. Instead of adding logic to our HTML, it is recommended to encapsulate this kind of state (or any derived value, for that matter) via functions defined on the computed key of our Vue instance.

    您可能會猜到, computed是一個對象,它描述了基于我們的數據模型的計算屬性。 建議不要通過在Vue實例的computed鍵上定義的函數來封裝這種狀態(或任何派生值),而不是向HTML添加邏輯。

Turning our attention now to the HTML, you will see that our markup has changed ever so slightly from the first CodePen. Specifically, we have made three changes.

現在將我們的注意力轉向HTML,您會發現我們的標記與第一個CodePen相比已經發生了很小的變化。 具體來說,我們進行了三處更改。

  1. We added the id twitterVue to the outermost div so that we could construct our Vue instance.

    我們將id twitterVue添加到最外面的div以便我們可以構造Vue實例。

<div id="twitterVue">...</div>

2. We added the v-model directive to our textarea, thereby creating a two-way binding between user input and our instance’s data model. Now, any time a user types in the textarea, the tweet attribute on our instance’s data model is automagically updated.

2.我們將v-model指令添加到了textarea ,從而在用戶輸入和實例的數據模型之間創建了雙向綁定 。 現在, textarea用戶輸入textarea ,實例數據模型上的tweet屬性就會自動更新。

<textarea v-model="tweet"></textarea>

3. We added the :disabled attribute to our button. The colon preceding disabled denotes that we would like to evaluate the content inside the quotes as a JavaScript expression. If we were to omit the colon, the content would be treated as a string. You’ll also note that we’ve added a few lines of CSS to give the disabled button a distinct visual styling.

3.我們在button添加了:disabled屬性。 之前的結腸disabled ,我們想引號為JavaScript表達式內的內容評價表示。 如果我們省略冒號,則內容將被視為字符串。 您還將注意到,我們添加了幾行CSS,為禁用按鈕提供了獨特的視覺樣式。

<button :disabled="tweetIsEmpty">Tweet</button>
...
button[disabled] {  cursor: not-allowed;  opacity: .5;}

4. We also added a computed property on our instance called tweetIsEmpty. Note that this property is actually a function that returns a boolean value based on the length of our data model’s tweet attribute. Vue makes it dead simple to access your data model both in the HTML (as shown above) and in the instance itself. Thanks to the magic of two-way data binding, this function is evaluated when the value of tweet is updated. When the function evaluates to true, our button is disabled, and vice-versa.

4.我們還在實例上添加了一個名為tweetIsEmpty的計算屬性。 請注意,此屬性實際上是一個函數 ,該函數根據數據模型的tweet屬性的長度返回一個布爾值。 Vue使在HTML(如上所示)和實例本身中訪問數據模型變得非常簡單。 得益于雙向數據綁定的魔力,當更新tweet的值時,將評估此功能。 當該函數的值為true時 ,我們的按鈕將被禁用,反之亦然。

tweetIsEmpty: function() {  return this.tweet.length === 0;}

Admittedly, this felt like smoke and mirrors when I first got started with Vue. What helped me was to literally see what was happening to our data model under the hood as I interacted with the component. Since we can easily access our data model in our HTML via the aforementioned curly brace syntax, we can build a quick, visual feedback loop. Score!

不可否認,當我剛開始使用Vue時,這就像煙霧和鏡子一樣。 真正幫助我的是,在與組件進行交互時,真正了解了我們的數據模型的幕后情況。 由于我們可以通過上述大括號語法輕松地訪問HTML中的數據模型,因此我們可以構建一個快速的視覺反饋循環。 得分!

<p>The value of <strong>tweet &lt;/strong>is: {{tweet}} </p><p>The value of <;strong>tweetIsEmpty</strong>is: {{ tweetIsEmpty}}</p>

Please feel free to repeat this step if anything along the way was confusing (either due to my poor writing or coding abilities, or due to Vue itself). Send a tweet or leave a comment if you have any particular questions.

如果途中發生任何混亂(由于我的寫作或編碼能力差,或由于Vue本身),請隨時重復此步驟。 如果您有任何特殊問題,請發送推文或發表評論。

步驟3:實施第二個功能-顯示剩余字符數 (Step 3: Implement the Second Feature — Show The Number of Characters Remaining)

Feature Description: As a user types, show the number of characters remaining (out of 140) in the tweet. If a user has entered more than 140 characters, disable the blue Tweet button.

功能描述 :當用戶鍵入內容時,顯示推文中剩余的字符數(共140個)。 如果用戶輸入的字符超過140個,請禁用藍色的Tweet按鈕。

So far we have learned about two-way data binding and computed properties, concepts that are at the very core of Vue. It is our lucky day, because we can leverage these concepts to build our next feature: showing the users how many characters (out of 140) remain, and disabling the button if this limit is eclipsed.

到目前為止,我們已經了解了雙向數據綁定和計算屬性,這些概念是Vue的核心。 這是我們的幸運日,因為我們可以利用這些概念來構建我們的下一個功能:向用戶顯示剩余的字符數(共140個),并且在超過此限制時禁用按鈕。

Once again, I will step you through both the JavaScript and HTML changes required to implement this feature.

再一次,我將引導您完成實現此功能所需JavaScript和HTML更改。

In our JavaScript, we have done a few things.

在我們JavaScript中,我們做了一些事情。

  1. As a housekeeping measure, we enumerated the max length of a tweet (140 characters) as a constant, MAX_TWEET_LENGTH.

    作為整理措施,我們將一條tweet的最大長度(140個字符)枚舉為常量MAX_TWEET_LENGTH

const MAX_TWEET_LENGTH = 140;

2. We added another computed property, charactersRemaining, which dynamically returns the difference between 140 and the length of the user-entered tweet.

2.我們添加了另一個計算出的屬性charactersRemaining ,該屬性動態返回140與用戶輸入的tweet的長度之間的差。

charactersRemaining: function() {  return MAX_TWEET_LENGTH - this.tweet.length;}

3. We renamed the old tweetIsEmpty property to tweetIsOutOfRange and updated the function’s logic accordingly. Note how we are using the computed charactersRemaining property to derive this value. Hooray for code reuse!

3.我們重命名了舊的tweetIsEmpty 屬性為tweetIsOutOfRange 并相應地更新了函數的邏輯。 注意我們如何使用計算出的charactersRemaining 屬性以得出值。 萬歲代碼重用!

tweetIsOutOfRange: function() {  return this.charactersRemaining == MAX_TWEET_LENGTH       || this.charactersRemaining < 0; }

On the HTML side of things, we only have to make a few changes, thanks to the power of Vue’s two-way data binding.

在HTML方面,由于Vue雙向數據綁定的強大功能,我們只需要進行一些更改。

<div class="flex items-center">  <span class="mr3 black-70">{{ charactersRemaining }}</span>  <button :disabled="tweetIsOutOfRange" class="button-reset bg-blue bn white f6 fw5 pv2 ph3 br2 dim">Tweet</button></div>

For the visual learners out there, watch the magic:

對于在那里的視覺學習者,請注意魔術:

步驟4:實施第三個功能:“剩余字符”指示器的條件樣式 (Step 4: Implement the Third Feature: Conditional Styling of “Characters Remaining” indicator)

Feature Description: When composing a Tweet, the color of the “characters remaining” indicator should change to dark red when only twenty characters remain, and light red when ten or fewer remain.

功能描述:編寫Tweet時,“僅剩余字符”指示器的顏色應在僅剩余20個字符時變為深紅色,而在剩余10個字符或更少時變為淺紅色。

Manipulating an element’s style or class can be cumbersome with jQuery, and Vue offers a much cleaner way of doing so. Vue’s approach feels more declarative, in that you describe how you want something’s style to change (based, for example, on a given state) and you let Vue do the heavy lifting.

使用jQuery操縱元素的樣式或類可能很麻煩,而Vue提供了一種更為簡潔的方法。 Vue的方法更具聲明性,因為您描述了如何更改某種樣式(例如,基于給定狀態),然后讓Vue進行繁重的工作。

In the context of this feature, our “characters remaining” indicator has two such states, and a corresponding CSS class for each.

在此功能的上下文中,我們的“剩余字符”指示器具有兩個這樣的狀態,并且每個狀態都有一個對應CSS類。

  1. When between ten and twenty characters remain, the indicator should have the dark-red class

    當剩余十到二十個字符時,指示器應具有dark-red等級

  2. When fewer than ten characters remain, the indicator should have the light-red class

    當剩余的字符少于十個時,指示器應具有light-red等級

By now your Vue brain should be shouting “COMPUTED PROPERTIES!” So, let us oblige this brain and wire up those properties.

到現在為止,您的Vue大腦應該在喊“計算機性能!” 因此,讓我們動腦筋,將這些屬性聯系起來。

underTwentyMark: function() {  return this.charactersRemaining <= 20     && this.charactersRemaining > 10;  },underTenMark: function() {  return this.charactersRemaining <= 10;}

With our logic in place, let us take a look at one of the ways in which Vue handles conditional styling: the v-bind:class directive. This directive expects an object whose keys are CSS classes, and whose values are the corresponding computed properties.

有了適當的邏輯,讓我們看一下Vue處理條件樣式的一種方式: v-bind:class指令。 該指令需要一個對象,其鍵是CSS類,其值是相應的計算屬性。

{ 'dark-red': underTwentyMark, 'light-red': underTenMark }

By adding the directive to the span tag that encloses our “characters remaining” indicator, we have completed our feature.

通過將指令添加到包圍“剩余字符”指示符的span標記中,我們完成了功能。

<span   v-bind:class="{ 'dark-red': underTwentyMark, 'light-red': underTenMark }">  {{ charactersRemaining }}</span>

Under the hood, and thanks to two-way data binding, Vue will handle the addition and removal of these classes as a function of the specified computed properties.

在后臺,由于采用了雙向數據綁定,Vue將根據指定的計算屬性來處理這些類的添加和刪除。

步驟5:實施第四個功能:“附加照片” UX (Step 5: Implement the Fourth Feature: “Attach Photo” UX)

Feature Description: Allow users to attach a single photo to their tweet via a file picker dialog. When the photo has been uploaded, show it beneath the textarea, and allow users to delete the attachment by clicking the image

功能描述:允許用戶通過文件選擇器對話框將單張照片附加到其推文中。 上傳照片后,將其顯示在textarea下方,并允許用戶通過單擊圖像來刪除附件

Fair warning: there is a lot going on in this section. The beauty is, despite this feature adding considerable functionality, we will not have to write that much code. So, let us start by breaking down the interaction design into steps.

合理的警告:本節中有很多事情要做。 美麗之處在于,盡管此功能添加了可觀的功能,但我們不必編寫那么多代碼。 因此,讓我們從將交互設計分解為幾個步驟開始。

  1. User clicks the “Add Photo” button

    用戶單擊“添加照片”按鈕
  2. User sees a file picker dialog and can select one photo to upload

    用戶會看到一個文件選擇器對話框,可以選擇要上傳的一張 照片

  3. Upon selecting the photo, a box appears underneath the textarea with the selected photo inside

    選擇照片后, textarea下方會出現一個框,其中包含所選照片

  4. User clicks the circular X button to remove the photo

    用戶單擊圓形的X按鈕以刪除照片

  5. User sees initial state from step 1

    用戶從步驟1中看到初始狀態

Up to this point, we have not yet done any event handling (listening to button clicks, input changes, etc). As you might expect, Vue makes it easy to handle such events by affording us the v-on directive (@ for short). By passing a method as a value of this directive, we can effectively listen to DOM events and run JavaScript when they are triggered.

到目前為止,我們尚未進行任何事件處理(監聽按鈕單擊,輸入更改等)。 如您所料,Vue通過提供v-on指令(簡稱為@)使處理此類事件變得容易。 通過將方法作為此偽指令的值傳遞,我們可以有效地偵聽DOM事件并在觸發它們時運行JavaScript。

Before diving into our feature work, some rapid-fire practice.

在深入研究特色作品之前,請先進行一些快速射擊練習。

Event handling is as easy as adding the @click directive to a given button and adding a corresponding method to the methods key on our Vue instance.

事件處理就像將@click指令添加到給定按鈕并在Vue實例上的methods鍵中添加相應方法一樣容易。

<button @click="logNameToConsole">Log User's Name<;/button>...methods: {  logNameToConsole: function() {    if( this.name !== 'Donald Trump' ) {      console.log(this.name);     } else {      console.warn('Sorry, I do not understand');    }  },}

Back to our feature work… In this step, our markup and JavaScript have changed in the following ways:

回到我們的功能工作…在這一步中,我們的標記和JavaScript已通過以下方式進行了更改:

  1. We added a button with an @click directive. When a user clicks this button, the triggerFileUpload method will get called.

    我們添加了帶有@click指令的button 。 當用戶單擊此按鈕時, triggerFileUpload方法將被調用。

<button @click="triggerFileUpload">...</button>

So, in our JavaScript, let us add a methods key to our Vue instance with said method inside, as well as a data attribute for our photo.

因此,在我們JavaScript中,讓我們在內部帶有上述方法的Vue實例中添加一個methods鍵,以及照片的data屬性。

data: { photo: null},computed: {},methods: {  triggerFileUpload: function() {    this.$refs.photoUpload.click(); // LOLWUT?  },}

2. It is notoriously difficult to style HTML5 file inputs. One workaround involves putting an input in the DOM and hiding it with CSS. In order for the browser to open the native file picker, this input must be clicked. How it gets clicked, and how the client handles what the user uploads, though, is a different matter.

2.眾所周知,設置HTML5文件輸入的樣式很難。 一種解決方法是將input放入DOM并用CSS隱藏。 為了使瀏覽器打開本機文件選擇器, 必須單擊此input 。 但是,如何單擊它以及客戶端如何處理用戶上傳的內容則是另一回事。

In our markup, we’ve added one such input and hidden it with a special hide class. We have also added a few other attributes worth calling out:

在我們的標記中,我們添加了一個這樣的input ,并使用特殊的hide類將其hide 。 我們還添加了一些值得一提的其他屬性:

<input ref="photoUpload" @change="handlePhotoUpload" type="file" class="hide">
  • The ref attribute is used to register a reference to a given DOM element. Given this reference, we can access the DOM element in our JavaScript code with this.$refs.photoUpload. Which means we can programmatically trigger a click() event on this element, thereby circumventing the challenge described above.

    ref屬性用于注冊給定DOM元素的引用 。 有了此參考,我們可以使用this.$refs.photoUpload訪問JavaScript代碼中的DOM元素。 這意味著我們可以以編程方式觸發此元素上的click()事件,從而規避了上述挑戰。

  • Clicking on the input is one thing; handling the file that the user uploads is another. Luckily, Vue allows us to attach a handler to the input’s change event via the @change directive. The method that we pass to this directive will be invoked after a user selects a file from the file picker. That method, handlePhotoUpload, is fairly straightforward

    單擊輸入是一回事; 處理用戶上傳的文件是另一回事。 幸運的是,Vue允許我們通過@change指令將處理程序附加到輸入的change事件。 用戶通過文件選擇器選擇文件后,將調用傳遞給該指令的方法。 該方法handlePhotoUploa d非常簡單

handlePhotoUpload: function(e) {  var self = this;  var reader = new FileReader();        reader.onload = function(e) {    // Set that base 64 string to our data model's 'photo' key    self.photo = (e.target.result);  }  // Read upload file as base 64  string  reader.readAsDataURL(e.target.files[0]); }

Take a deep breath, because we are almost done with this feature!

深呼吸,因為我們幾乎已完成此功能!

Once a user has uploaded a photo, we need to show a box underneath the textarea with the selected photo inside. Just as the conditional styling of elements is a breeze with Vue, so too is the conditional rendering, or display of elements. You’ll note that in our HTML, we have added the following markup underneath the textarea.

用戶上傳照片后,我們需要在textarea下方顯示一個框,其中包含所選照片。 正如元素的條件樣式對Vue輕而易舉一樣,條件渲染或元素顯示也是如此。 您會注意到,在我們HTML中,我們在textarea下方添加了以下標記。

<div v-if="photoHasBeenUploaded">  <figure>    &lt;button @click="removePhoto">      ...    &lt;/button>    <img v-bind:src="photo">  </figure></div>

Vue offers a handful of template helpers (v-if, v-show, v-else , etc) to help you show and hide content conditionally. When the JavaScript expression passed to this directive evaluates to true, the element is rendered, and vice-versa.

Vue提供了一些模板助手( v-ifv-show, v-else等)來幫助您有條件地顯示和隱藏內容。 當傳遞給該指令JavaScript表達式的值為true時,將呈現元素,反之亦然。

In our case, we added a v-if statement that evaluates the computed property photoHasBeenUploaded .

在我們的例子中,我們添加了一個v-if語句,該語句評估計算出的屬性photoHasBeenUploaded

photoHasBeenUploaded: function() {  return this.photo !== null;}

When that function evaluates to true — when the photo key of our data model is not equal to null — the entire div gets rendered. Voilà!

當該函數的值為true時(當我們的數據模型的照片鍵不等于null時),整個div就會被渲染。 瞧!

And inside that div we render two elements:

在該div內,我們呈現兩個元素:

  1. The image that was attached, by passing the contents of our data model’s photo key to Vue’s v-bind:src directive

    通過將數據模型的photo密鑰的內容傳遞給Vue的v-bind:src指令,從而附加了圖像

  2. A delete button that features another example of the@click handler, this particular one invoking a function that “removes” the photo by setting our data model’s photo key to null.

    一個刪除按鈕,具有@click處理程序的另一個示例,該特定按鈕調用一個通過將數據模型的photo鍵設置為null來“刪除”照片的功能。

removePhoto: function() {  this.photo = null;}

We are almost there.

我們就快到了。

第6步:更正,用戶可以附加“ 照片(Step 6: Correction, user can attach “photos)

So, we can effectively handle a user attaching one photo to the Tweet, but what if she would like to upload many photos?

因此,我們可以有效地處理用戶在Tweet上附加一張照片的情況,但是如果她想上傳多張照片怎么辦?

By now, you should be thinking something to the effect of: “I guess the only significant change here is being able to show multiple images in that box that appears conditionally beneath the textarea, considering we have already wired up our event handlers…” And you are correct! Let us take a look at the steps we need to follow

到現在為止,您應該在考慮以下效果:“我想這里唯一的重大變化是,考慮到我們已經連接了事件處理程序,因此能夠在有條件顯示在文本區域下方的框中顯示多個圖像……”你是對的! 讓我們看看我們需要遵循的步驟

  1. We need to update our data model by changing photo to photos, the new key being an array of base64 strings (not a single base64 string)

    我們需要通過將photo更改為photos來更新數據模型,新鍵是base64字符串數組 (而不是單個base64字符串)

data: {  photos: []},

2. We need to update our computed property photoHasBeenUploaded to check against the length of our new photos key, which is now an array.

2.我們需要更新計算的屬性photoHasBeenUploaded以檢查新的photos密鑰(現在是數組)的長度。

photoHasBeenUploaded: function() {  return this.photos.length > 0;}

3. We need to update our input @change handler to loop over the uploaded files and push them onto our photos key.

3.我們需要更新輸入@change處理程序以遍歷上載的文件,并將其推入我們的photos鍵。

handlePhotoUpload: function(e) {  var self = this;  var files = e.target.files;
for(let i = 0; i < files.length; i++) {    let reader = new FileReader();
reader.onloadend = function(evt) {      self.photos.push(evt.target.result);    }
reader.readAsDataURL(files[i]);  }},

On the HTML side, however, we must embark into new territory. Iterating over data and rendering content with jQuery can be cumbersome.

但是,在HTML方面,我們必須踏入新的領域。 使用jQuery遍歷數據并呈現內容可能很麻煩。

var array = [1, 2, 3, 4, 5];var newHTML = [];for (var i = 0; i < array.length; i++) {    console.log('UGHHHHHH');    newHTML.push('<span>' + array[i] + '</span>');}$(".element").html(newHTML.join(""));

Thankfully, Vue offers an abstraction over this procedure by way of the v-for directive. This directive expects you to provide an expression in the form of (thing, index) in collectionOfThings, where collectionOfThings is the source array, thing is an alias for the array element being iterated on, and index is, well, the index of that element.

值得慶幸的是,Vue通過v-for指令對該過程進行了抽象。 該指令希望您以(thing, index) in collectionOfThings 的形式 (thing, index) in collectionOfThings 提供一個表達式 ,其中collectionOfThings是源數組, thing是要迭代的數組元素的別名,而index是該元素的索引。

A prototypical example might look like this:

一個典型的示例可能如下所示:

Where before we had a singular figure element for the user-uploaded photo, we will now have N figure tags corresponding to the length of the photos source array.

在我們為用戶上傳的照片使用單數figure元素之前,現在將有N個 figure標簽對應于photos源陣列的長度。

Lucky for us, our markup doesn’t have to change too drastically since the overall structure of the design is still the same.

對我們來說幸運的是,由于設計的總體結構仍然相同,因此我們的標記不必進行太大的更改。

<figure v-for="(photo, index) in photos">  &lt;button @click="removePhoto(index)">    ...  </button>  <img v-bind:src="photo" class="h3 w3"></figure>

The one change that we need to make revolves around the removePhoto method which, before, set the singular photo key on our data model to null. Now, since we have N number of photos, we must pass the element’s index to the removePhoto method and pull that element out of the array.

我們需要進行的一項更改涉及removePhoto方法,該方法之前將數據模型上的removePhoto photo鍵設置為null 。 現在,由于有N張照片,我們必須將元素的索引傳遞給removePhoto方法,然后將該元素從數組中拉出。

removePhoto: function(index) {  this.photos.splice(index, 1);}

步驟7:動畫+額外信用 (Step 7: Animation + Extra Credit)

In Twitter’s UI, the “Compose Tweet” component opens in a modal. For our grand finale, I would like to apply all of the Vue techniques we have learned so far and introduce one more: transitions.

在Twitter的UI中,“組合推文”組件以模式形式打開。 對于大結局,我想應用到目前為止所學的所有Vue技術,并介紹一種: transitions 。

A word of caution, transitions are a vast subject in Vue land. We are going to examine and implement a thin slice of this functionality, namely integrating a 3rd party animation library, Velocity JS, with Vue.

請注意,過渡是Vue領域中的一個巨大主題。 我們將檢查并實現此功能的一小部分,即將第3方動畫庫Velocity JS與Vue集成在一起。

In a nutshell, Vue provides a transition component that allows you to add enter/leave animations for the element contained within, provided the element is set to be displayed conditionally via, for example, a v-if or v-show directive.

簡而言之,Vue提供了一個transition組件,允許您為其中包含的元素添加輸入/離開動畫,前提是該元素被設置為通過例如v-ifv-show指令有條件地顯示。

<transition   name="modal-transition"  v-on:enter="modalEnter"   v-on:leave="modalLeave">    <div v-if="modalShowing">       <!-- Our modal contents goes here ! -->    </div></transition>

In our example, we have attached two methods that correspond with two events in the transition lifecycle: v-on:enter and v-on:leave. We have thusly added these method definitions to our Vue instance, deferring to Velocity JS to fade our modal in and out.

在我們的示例中,我們附加了與過渡生命周期中的兩個事件相對應的兩個方法: v-on:enterv-on:leave 。 因此,我們已將這些方法定義添加到我們的Vue實例中,順應Velocity JS fade我們的模態。

methods: {  modalEnter: function(el, done) {    Velocity(el, 'fadeIn', { duration: 300, complete: done, display: 'flex' })  },  modalLeave: function(el, done) {    Velocity(el, 'fadeOut', { duration: 300, complete: done })  }}

As mentioned above, the transition will fire when the element contained within is conditionally set to display. So, on the inner div of our transition component, we have added a v-if declaration whose value is a boolean modalShowing. Let us update our instance’s data model accordingly.

如上所述,當包含在其中的元素被有條件地設置為顯示時, transition將觸發。 因此,在transition組件的內部div上,添加了一個v-if聲明,該聲明的值是boolean modalShowing 。 讓我們相應地更新實例的數據模型。

data: {  modalShowing: false}

Now, when we want to show the modal, all we have to do is set that boolean to true!

現在,當我們想要顯示模態時,我們要做的就是將boolean設置為true!

<button @click="showModal">Compose Tweet</button>

And write a method to match.

并編寫一個匹配的方法。

hideModal: function() {  this.modalShowing = false;},showModal: function() {  this.modalShowing = true;},

With some CSS trickery, we have also attached a click event handler to the backdrop, so users can hide the modal. Score!

借助一些CSS技巧,我們還將click事件處理程序附加到了背景上,以便用戶可以隱藏模式。 得分!

<div   @click="hideModal"  class="backdrop"></div>

結論 (Conclusion)

Well, I hope that was not too painful (and that you learned a thing or two along the way). We only took a look at a small sliver of what Vue has to offer, though, as mentioned above, these concepts are crucial to unlocking the potential of Vue.

好吧,我希望那不是太痛苦(并且您在一路上學到了一兩個東西)。 我們只看了一小部分Vue提供的功能,但是,如上所述,這些概念對于釋放Vue的潛力至關重要。

I admit, it is unfair to compare Vue to jQuery. They are products of different times, with quite different use cases. However, for those who have struggled their way to learn DOM manipulation and event handling through jQuery, I hope these concepts are a breath of fresh air that you can apply to your workflow.

我承認,將Vue與jQuery比較是不公平的。 它們是不同時期的產品,具有完全不同的用例。 但是,對于那些為通過jQuery學習DOM操作和事件處理而苦苦掙扎的人,我希望這些概念能給您帶來新鮮的氣息,您可以將其應用于您的工作流。

翻譯自: https://www.freecodecamp.org/news/vue-js-introduction-for-people-who-know-just-enough-jquery-to-get-by-eab5aa193d77/

jquery.vue.js

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395880.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395880.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395880.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python 矩陣獲取行數_4個最佳項目創意的代碼片段和示例,旨在為Python和機器學習構建出色的簡歷!...

點擊上方“小白學視覺”&#xff0c;選擇加"星標"或“置頂”重磅干貨&#xff0c;第一時間送達一篇文章帶你了解4個最佳項目創意的代碼片段和示例Python是一種特殊的編程語言&#xff0c;適用于從初學者到中級用戶。由于它的靈活性&#xff0c;它正逐漸成為一種非常流…

Android 多狀態加載布局的開發 Tips

2019獨角獸企業重金招聘Python工程師標準>>> 什么是多狀態 Layout 對于大多數 App 而言&#xff0c;項目中都有多狀態加載 View 這種需求&#xff0c;如下圖所示。 對應到開發中&#xff0c;我們通常會開發一個對應的自定義 layout 用于根據頁面不同的狀態來顯示不同…

XML解析之JAXP案例詳解

根據一個CRUD的案例&#xff0c;對JAXP解析xml技術&#xff0c;進行詳細的解釋&#xff1a; 首先&#xff0c;已知一個xml文件中的數據如下&#xff1a; <?xml version"1.0" encoding"UTF-8" standalone"no"?> <書架><書 出版社…

隨機梯度下降

1.SGD 代價函數通常可以分解成每個樣本的代價函數的總和轉載于:https://www.cnblogs.com/bigcome/p/10042800.html

iis mysql5.7_手動配置網站環境 IIS 10+PHP 7.1+MySQL 5.7

之前配置環境一直用的一鍵安裝包&#xff0c;不管是phpStudy還是lnmp&#xff0c;昨天嘗試在自己電腦配置一下iis的環境&#xff0c;也踩了一些坑&#xff0c;整理了一下。測試電腦是Windows10&#xff0c;理論上Win7和IIS7.5都支持的。安裝 IIS1&#xff1a;控制面板 > 程序…

如何使用Apache的Prediction IO Machine Learning Server構建推薦引擎

by Vaghawan Ojha通過瓦哈萬歐哈(Vaghawan Ojha) 如何使用Apache的Prediction IO Machine Learning Server構建推薦引擎 (How to build a recommendation engine using Apache’s Prediction IO Machine Learning Server) This post will guide you through installing Apache…

JavaScript DOM編程藝術第二版學習(1/4)

接下來項目需要網頁相關知識&#xff0c;故在大牛的指引下前來閱讀本書。 記錄方式&#xff1a;本書分四部分閱讀&#xff0c;完成閱讀之后會多寫一篇包括思維導圖的算是閱讀指南的東西&#xff0c;瀏覽的童鞋看著指南可以跳過一些不必要的坑~ 當前水平&#xff1a;HTML&CS…

github開源大項目_GitHub剛剛發布了一份大規模的開源指南

github開源大項目Here are three links worth your time:這是三個值得您花費時間的鏈接&#xff1a; GitHub just released a massive guide to contributing to open source (5 to 60 minute read) GitHub剛剛發布了一份有關開源的大型指南( 閱讀5至60分鐘 ) A new way to br…

mysql中where條件判斷語句_MySQL Where 條件語句介紹和運算符小結

WHERE 條件有時候操作數據庫時&#xff0c;只操作一些有條件限制的數據&#xff0c;這時可以在SQL語句中添加WHERE子句來規定數據操作的條件。語法&#xff1a;SELECT column,… FROM tb_name WHERE definitionWHERE 關鍵字后面接有效的表達式(definition)&#xff0c;該表達式…

node webkit(nw.js) 設置自動更新

原理&#xff1a;把更新的文件放在服務器上&#xff0c;設置一個客戶端版本號&#xff0c;每次打開客戶端的時候&#xff0c;通過接口獲取服務器上的版本&#xff0c;如果高于本地的版本就下載服務器上的代碼&#xff0c;低于或等于就不更新 1 <script>2 var htt…

個人工作總結04(沖刺二)

今天是團隊第二次沖刺階段開始的第04天&#xff0c;我的工作總結如下&#xff1a; 一、昨天干了什么&#xff1f; 知識圈查詢功能 基本實現數據庫查詢 (未完成) 二、今天準備做什么&#xff1f; 知識圈查詢功能 基本實現數據庫查詢 三、遇到了什么困難&#xff1f; 數據庫訪問出…

mysql8.0版1130_navicat premium連接mysql 8.0報錯error 10061和error1130問題

昨天安裝了最新版的mysql navicat premium, 但沒來得及測試使用Navicat連接。今天上班時&#xff0c;使用Navicat premium連接mysql時&#xff0c;出現報錯ERROR 2003 (HY000): Can’t connect to MySQL server on ‘1XX.XX.XX.XX’ (10061).起初以為是mysql沒有安裝成功&#…

freecodecamp_為什么您一定要參與freeCodeCamp的一個研究小組

freecodecampby Frederick Ige弗雷德里克艾格(Frederick Ige) 為什么您一定要參與freeCodeCamp的一個研究小組 (Why you should definitely get involved with one of freeCodeCamp’s study groups) I’m writing this article in hopes of convincing you to take advantage…

C語言運行時數據結構

段&#xff08;Segment&#xff09;&#xff1a; 對象文件/可執行文件&#xff1a; SVr4 UNIX上被稱為ELF&#xff08;起初"Extensible Linker Format", 現在"Executable and Linking Format"&#xff09;文件。BSD UNIX上被稱為a.out。這些格式都具有段的…

Java掛起線程

2019獨角獸企業重金招聘Python工程師標準>>> 不優雅的suspend import java.util.concurrent.TimeUnit;public class SuspendTest {static Object lock new Object();SuppressWarnings("deprecation")public static void main(String[] args) {Suspend s1…

Hibernate包及相關工具包下載地址

Hibernate包及相關工具包下載地址&#xff1a; http://prdownloads.sourceforge.net/hibernate/ 這里包含所有hibernate各個版本的包下載&#xff0c;且提供了 Middlegen Hibernate及hibernate-extensions包的下載。這兩個包是用于自動生成相就的JAVA和*.hb…

init(coder:)_2018年《 New Coder》調查:31,000人告訴我們他們如何學習編碼并在工作中獲得工作…

init(coder:)More than 31,000 people responded to our 2018 New Coder Survey, granting researchers an unprecedented glimpse into how adults are learning to code.超過31,000人對我們的2018年《新編碼器調查》做出了回應&#xff0c;使研究人員對成年人如何學習編碼有了…

Redis源碼解析:21sentinel(二)定期發送消息、檢測主觀下線

六&#xff1a;定時發送消息 哨兵每隔一段時間&#xff0c;會向其所監控的所有實例發送一些命令&#xff0c;用于獲取這些實例的狀態。這些命令包括&#xff1a;”PING”、”INFO”和”PUBLISH”。 “PING”命令&#xff0c;主要用于哨兵探測實例是否活著。如果對方超過一段時間…

[SDOI2018]原題識別

題解&#xff1a; 。。感覺挺煩得 而且我都沒有注意到樹隨機這件事情。。 就寫個30分的莫隊。。 #include <bits/stdc.h> using namespace std; #define rint register int #define IL inline #define rep(i,h,t) for (int ih;i<t;i) #define dep(i,t,h) for (int it;…

django app中擴展users表

app models中編寫新的User1 # _*_ coding:utf-8 _*_2 from __future__ import unicode_literals34 from django.db import models5 from django.contrib.auth.models import AbstractUser # 繼承user67 # Create your models here.8910 class UserProfile(AbstractUser):11 …