From 3601b7bb982e958927e069715cfe07430bce7196 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Thu, 15 Jul 2021 12:59:34 -0400 Subject: delete pages that were never translated from en-US (es, part 1) (#1547) --- .../es/learn/css/css_layout/positioning/index.html | 469 ------------ .../client-side_web_apis/fetching_data/index.html | 373 ---------- .../server-side/express_nodejs/mongoose/index.html | 801 --------------------- .../vue_getting_started/index.html | 295 -------- 4 files changed, 1938 deletions(-) delete mode 100644 files/es/learn/css/css_layout/positioning/index.html delete mode 100644 files/es/learn/javascript/client-side_web_apis/fetching_data/index.html delete mode 100644 files/es/learn/server-side/express_nodejs/mongoose/index.html delete mode 100644 files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html (limited to 'files/es/learn') diff --git a/files/es/learn/css/css_layout/positioning/index.html b/files/es/learn/css/css_layout/positioning/index.html deleted file mode 100644 index 3deb33b91f..0000000000 --- a/files/es/learn/css/css_layout/positioning/index.html +++ /dev/null @@ -1,469 +0,0 @@ ---- -title: Positioning -slug: Learn/CSS/CSS_layout/Positioning -translation_of: Learn/CSS/CSS_layout/Positioning ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout/Practical_positioning_examples", "Learn/CSS/CSS_layout")}}
- -

El posicionamiento permite sacar elementos del flujo normal del diseño del documento, y hacer que se comporten de manera distinta, por ejemplo sentarse encima de otro o permanecer en el mismo lugar dentro de la ventana navegador. Este artículo explica los diferentes valores {{cssxref("position")}}, y como usarlos.

- - - - - - - - - - - - -
Requisitos:HTML básico (Aprende  Introducción a HTML), y una idea de cómo trabaja CSS (Aprende  Introducción a CSS.)
Objetivos:Entender como trabajar con posicionamiento CSS.
- -

Flujo del Documento

- -

El posicionamiento es un tema bastante complejo, así que antes de profundizar en el código volvamos a examinar y ampliar un poco la teoría del diseño para darnos una idea de cómo funciona esto.

- -

First of all, individual element boxes are laid out by taking the elements' content, then adding any padding, border and margin around them — it's that box model thing again, which we looked at earlier. By default, a block level element's content is 100% of the width of its parent element, and as tall as its content. Inline elements are all tall as their content, and as wide as their content. You can't set width or height on inline elements — they just sit inside the content of block level elements. If you want to control the size of an inline element in this manner, you need to set it to behave like a block level element with display: block;.

- -

That explains individual elements, but what about how elements interact with one another? The normal layout flow (mentioned in the layout introduction article) is the system by which elements are placed inside the browser's viewport. By default, block level elements are laid out vertically in the viewport — each one will appear on a new line below the last one, and they will be separated by any margin that is set on them.

- -

Inline elements behave differently — they don't appear on new lines; instead, they sit on the same line as one another and any adjacent (or wrapped) text content, as long as there is space for them to do so inside the width of the parent block level element. If there isn't space, then the overflowing text or elements will move down to a new line.

- -

If two adjacent elements both have margin set on them and the two margins touch, the larger of the two remains, and the smaller one disappears — this is called margin collapsing, and we have met this before too.

- -

Let's look at a simple example that explains all this:

- -
<h1>Basic document flow</h1>
-
-<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p>
-
-<p>By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p>
-
-<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p>
-
-<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements will <span>wrap onto a new line if possible (like this one containing text)</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p>
- -
body {
-  width: 500px;
-  margin: 0 auto;
-}
-
-p {
-  background: aqua;
-  border: 3px solid blue;
-  padding: 10px;
-  margin: 10px;
-}
-
-span {
-  background: red;
-  border: 1px solid black;
-}
- -

{{ EmbedLiveSample('Document_flow', '100%', 500) }}

- -

We will be revisiting this example a number of times as we go through this article, as we show the effects of the different positioning options available to us.

- -

We'd like you to follow along with the exercises on your local computer, if possible — grab a copy of 0_basic-flow.html from our Github repo (source code here) and use that as a starting point.

- -

Introducing positioning

- -

The whole idea of positioning is to allow us to override the basic document flow behaviour described above, to produce interesting effects. What if you want to slightly alter the position of some boxes inside a layout from their default layout flow position, to give a slightly quirky, distressed feel? Positioning is your tool. Or if you want to create a UI element that floats over the top of other parts of the page, and/or always sits in the same place inside the browser window no matter how much the page is scrolled? Positioning makes such layout work possible.

- -

There are a number of different types of positioning that you can put into effect on HTML elements. To make a specific type of positioning active on an element, we use the {{cssxref("position")}} property.

- -

Static positioning

- -

Static positioning is the default that every element gets — it just means "put the element into its normal position in the document layout flow — nothing special to see here."

- -

To demonstrate this, and get your example set up for future sections, first add a class of positioned to the second {{htmlelement("p")}} in the HTML:

- -
<p class="positioned"> ... </p>
- -

Now add the following rule to the bottom of your CSS:

- -
.positioned {
-  position: static;
-  background: yellow;
-}
- -

If you now save and refresh, you'll see no difference at all, except for the updated background color of the 2nd paragraph. This is fine — as we said before, static positioning is the default behaviour!

- -
-

Note: You can see the example at this point live at 1_static-positioning.html (see source code).

-
- -

Relative positioning

- -

Relative positioning is the first position type we'll take a look at. This is very similar to static positioning, except that once the positioned element has taken its place in the normal layout flow, you can then modify its final position, including making it overlap other elements on the page. Go ahead and update the position declaration in your code:

- -
position: relative;
- -

If you save and refresh at this stage, you won't see a change in the result at all — so how do you modify the element's position? You need to use the {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} properties, which we'll explain in the next section.

- -

Introducing top, bottom, left, and right

- -

{{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} are used alongside {{cssxref("position")}} to specify exactly where to move the positioned element to. To try this out, add the following declarations to the .positioned rule in your CSS:

- -
top: 30px;
-left: 30px;
- -
-

Note: The values of these properties can take any units you'd logically expect — pixels, mm, rems, %, etc.

-
- -

If you now save and refresh, you'll get a result something like this:

- - - -

{{ EmbedLiveSample('Introducing_top_bottom_left_and_right', '100%', 500) }}

- -

Cool, huh? Ok, so this probably wasn't what you were expecting — why has it moved to the bottom and right if we specified top and left? Illogical as it may initially sound, this is just the way that relative positioning works — you need to think of an invisible force that pushes the side of the positioned box, moving it in the opposite direction. So for example, if you specify top: 30px;, a force pushes the top of the box, causing it to move downwards by 30px.

- -
-

Note: You can see the example at this point live at 2_relative-positioning.html (see source code).

-
- -

Absolute positioning

- -

Absolute positioning brings very different results. Let's try changing the position declaration in your code as follows:

- -
position: absolute;
- -

If you now save and refresh, you should see something like so:

- - - -

{{ EmbedLiveSample('Absolute_positioning', '100%', 420) }}

- -

First of all, note that the gap where the positioned element should be in the document flow is no longer there — the first and third elements have closed together like it no longer exists! Well, in a way, this is true. An absolutely positioned element no longer exists in the normal document layout flow. Instead, it sits on its own layer separate from everything else. This is very useful — it means that we can create isolated UI features that don't interfere with the position of other elements on the page — for example popup information boxes and control menus, rollover panels, UI features that can be dragged and dropped anywhere on the page, and so on.

- -

Second, notice that the position of the element has changed — this is because {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} behave in a different way with absolute positioning. Instead of specifying the direction the element should move in, they specify the distance the element should be from each containing element's sides. So in this case, we are saying that the absolutely positioned element should sit 30px from the top of the "containing element", and 30px from the left.

- -
-

Note: You can use {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} to resize elements if you need to. Try setting top: 0; bottom: 0; left: 0; right: 0; and margin: 0; on your positioned elements and see what happens! Put it back again afterwards...

-
- -
-

Note: Yes, margins still affect positioned elements. Margin collapsing doesn't, however.

-
- -
-

Note: You can see the example at this point live at 3_absolute-positioning.html (see source code).

-
- -

Positioning contexts

- -

Which element is the "containing element" of an absolutely positioned element? By default, it is the {{htmlelement("html")}} element — the positioned element is nested inside the {{htmlelement("body")}} in the HTML source, but in the final layout, it is 30px away from the top and left of the edge of the page, which is the {{htmlelement("html")}} element. This is more accurately called the element's positioning context.

- -

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's other ancestors — one of the elements it is nested inside (you can't position it relative to an element it is not nested inside). To demonstrate this, add the following declaration to your body rule:

- -
position: relative;
- -

This should give the following result:

- - - -

{{ EmbedLiveSample('Positioning_contexts', '100%', 420) }}

- -

The positioned element now sits relative to the {{htmlelement("body")}} element.

- -
-

Note: You can see the example at this point live at 4_positioning-context.html (see source code).

-
- -

Introducing z-index

- -

All this absolute positioning is good fun, but there is another thing we haven't considered yet — when elements start to overlap, what determines which elements appear on top of which other elements? In the example we've seen so far, we only have one positioned element in the positioning context, and it appears on the top, since positioned elements win over non-positioned elements. What about when we have more than one?

- -

Try adding the following to your CSS, to make the first paragraph absolutely positioned too:

- -
p:nth-of-type(1) {
-  position: absolute;
-  background: lime;
-  top: 10px;
-  right: 30px;
-}
- -

At this point you'll see the first paragraph colored green, moved out of the document flow, and positioned a bit above from where it originally was. It is also stacked below the original .positioned paragraph, where the two overlap. This is because the .positioned paragraph is the second paragraph in the source order, and positioned elements later in the source order win over positioned elements earlier in the source order.

- -

Can you change the stacking order? Yes, you can, by using the {{cssxref("z-index")}} property. "z-index" is a reference to the z-axis. You may recall from previous points in the source where we discussed web pages using horizontal (x-axis) and vertical (y-axis) coordinates to work out positioning for things like background images and drop shadow offsets. (0,0) is at the top left of the page (or element), and the x- and y-axes run across to the right and down the page (for left to right languages, anyway.)

- -

Web pages also have a z-axis — an imaginary line that runs from the surface of your screen, towards your face (or whatever else you like to have in front of the screen). {{cssxref("z-index")}} values affect where positioned elements sit on that axis — positive values move them higher up the stack, and negative values move them lower down the stack. By default, positioned elements all have a z-index of auto, which is effectively 0.

- -

To change the stacking order, try adding the following declaration to your p:nth-of-type(1) rule:

- -
z-index: 1;
- -

You should now see the finished example:

- - - -

{{ EmbedLiveSample('Introducing_z-index', '100%', 400) }}

- -

Note that z-index only accepts unitless index values; you can't specify that you want one element to be 23 pixels up the Z-axis — it doesn't work like that. Higher values will go above lower values, and it is up to you what values you use. Using 2 and 3 would give the same effect as 300 and 40000.

- -
-

Note: You can see the example at this point live at 5_z-index.html (see source code).

-
- -

Fixed positioning

- -

There is one more type of positioning to cover — fixed. This works in exactly the same way as absolute positioning, with one key difference — whereas absolute positioning fixes an element in place relative to the {{htmlelement("html")}} element or its nearest positioned ancestor, fixed positioning fixes an element in place relative to the browser viewport itself. This means that you can create useful UI items that are fixed in place, like persisting navigation menus.

- -

Let's put together a simple example to show what we mean. First of all, delete the existing p:nth-of-type(1) and .positioned rules from your CSS.

- -

Now, update the body rule to remove the position: relative; declaration and add a fixed height, like so:

- -
body {
-  width: 500px;
-  height: 1400px;
-  margin: 0 auto;
-}
- -

Now we're going to give the {{htmlelement("h1")}} element position: fixed;, and get it to sit at the top center of the viewport. Add the following rule to your CSS:

- -
h1 {
-  position: fixed;
-  top: 0;
-  width: 500px;
-  margin: 0 auto;
-  background: white;
-  padding: 10px;
-}
- -

The top: 0; is required to make it stick to the top of the screen; we then give the heading the same width as the content column and use the faithful old margin: 0 auto; trick to center it. We then give it a white background and some padding, so the content won't be visible underneath it.

- -

If you save and refresh now, you'll see a fun little effect whereby the heading stays fixed, and the content appears to scroll up and disappear underneath it. But we could improve this more — at the moment some of the content starts off underneath the heading. This is because the positioned heading no longer appears in the document flow, so the rest of the content moves up to the top. We need to move it all down a bit; we can do this by setting some top margin on the first paragraph. Add this now:

- -
p:nth-of-type(1) {
-  margin-top: 60px;
-}
- -

You should now see the finished example:

- - - -

{{ EmbedLiveSample('Fixed_positioning', '100%', 400) }}

- -
-

Note: You can see the example at this point live at 6_fixed-positioning.html (see source code).

-
- -

Experimental: position sticky

- -

There is a new positioning value available called position: sticky, support for which is not very widespread yet. This is basically a hybrid between relative and fixed position, which allows a positioned element to act like it is relatively positioned until it is scrolled to a certain threshold point (e.g. 10px from the top of the viewport), after which it becomes fixed.  See our position: sticky reference entry for more details and an example.

- -

Summary

- -

I'm sure you had fun playing with basic positioning — it is one of the essential tools behind creating complex CSS layouts and UI features. With that in mind, in the next article we'll have even more fun with positioning — there we'll go a step further and start to build up some real world useful things with it.

- -

{{PreviousMenuNext("Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout/Practical_positioning_examples", "Learn/CSS/CSS_layout")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/es/learn/javascript/client-side_web_apis/fetching_data/index.html b/files/es/learn/javascript/client-side_web_apis/fetching_data/index.html deleted file mode 100644 index ab34b8c319..0000000000 --- a/files/es/learn/javascript/client-side_web_apis/fetching_data/index.html +++ /dev/null @@ -1,373 +0,0 @@ ---- -title: Fetching data from the server -slug: Learn/JavaScript/Client-side_web_APIs/Fetching_data -translation_of: Learn/JavaScript/Client-side_web_APIs/Fetching_data ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/Client-side_web_APIs/Manipulating_documents", "Learn/JavaScript/Client-side_web_APIs/Third_party_APIs", "Learn/JavaScript/Client-side_web_APIs")}}
- -

Otra tarea muy común en páginas web y en aplicaciones es tomar elementos individuales de datos desde el servidor para actualizar secciones de la página web sin tener que cargar toda una nueva página. Este aparentemente pequeño detalle tiene un gran impacto en el desempeño y comportamiento de los sitios, por eso en este artículo, explicaremos el concepto y veremos las tecnologías que hacen esto posible, como ser XHLHttpRequest y FetchAPI. 

- - - - - - - - - - - - -
Prerequisitos:JavaScript básico (ver first steps, building blocks, JavaScript objects),  basics of Client-side APIs
Objetivo:Aprender como extraer datos desde el servidor y usarlo para cargar contenido en la página web. 
- -

Cúal es el problema aquí?

- -

Originalmente cargar páginas en la web era simple  — tu enviabas una solicitud de la página web al servidor, y si no había ningún problema, los servicios encargados de la página web la descargaban y mostraban en tu computadora.

- -

A basic representation of a web site architecture

- -

El problema con este modelo es que si tu quieres actualizar cualquier parte de la página, por ejemplo, mostrar el nuevo set de productos o cargar una nueva página, tu tenías que cargar toda la página de nuevo. Esto es extremadamente un desperdicio y resultaba ser una experiencia pobre al usuario, especialmente cuando la página es más grande y más compleja. 

- -

Introduciendo Ajax

- -

This led to the creation of technologies that allow web pages to request small chunks of data (such as HTML, {{glossary("XML")}}, JSON, or plain text) and display them only when needed, helping to solve the problem described above.

- -

This is achieved by using APIs like {{domxref("XMLHttpRequest")}} or — more recently — the Fetch API. These technologies allow web pages to directly handle making HTTP requests for specific resources available on a server and formatting the resulting data as needed before it is displayed.

- -
-

Note: In the early days, this general technique was known as Asynchronous JavaScript and XML (Ajax), because it tended to use {{domxref("XMLHttpRequest")}} to request XML data. This is normally not the case these days (you'd be more likely to use XMLHttpRequest or Fetch to request JSON), but the result is still the same, and the term "Ajax" is still often used to describe the technique.

-
- -

A simple modern architecture for web sites

- -

The Ajax model involves using a web API as a proxy to more intelligently request data rather than just having the browser reload the entire page. Let's think about the significance of this:

- -
    -
  1. Go to one of your favorite information-rich sites, like Amazon, YouTube, CNN, etc., and load it.
  2. -
  3. Now search for something, like a new product. The main content will change, but most of the surrounding information, like the header, footer, navigation menu, etc., will stay the same.
  4. -
- -

This is a really good thing because:

- - - -

To speed things up even further, some sites also store assets and data on the user's computer when they are first requested, meaning that on subsequent visits they use the local versions instead of downloading fresh copies when the page is first loaded. The content is only reloaded from the server when it has been updated.

- -

A basic web app data flow architecture

- -

A basic Ajax request

- -

Let's look at how such a request is handled, using both {{domxref("XMLHttpRequest")}} and Fetch. For these examples, we'll request data out of a few different text files and use them to populate a content area.

- -

This series of files will act as our fake database; in a real application, we'd be more likely to use a server-side language like PHP, Python, or Node to request our data from a database. Here, however, we want to keep it simple and concentrate on the client-side part of this.

- -

XMLHttpRequest

- -

XMLHttpRequest (which is frequently abbreviated to XHR) is a fairly old technology now — it was invented by Microsoft in the late '90s, and has been standardized across browsers for quite a long time.

- -
    -
  1. -

    To begin this example, make a local copy of ajax-start.html and the four text files — verse1.txt, verse2.txt, verse3.txt, and verse4.txt — in a new directory on your computer. In this example, we will load a different verse of the poem (which you may well recognize) via XHR when it's selected in the drop-down menu.

    -
  2. -
  3. -

    Just inside the {{htmlelement("script")}} element, add the following code. This stores a reference to the {{htmlelement("select")}} and {{htmlelement("pre")}} elements in variables and defines an {{domxref("GlobalEventHandlers.onchange","onchange")}} event handler function so that when the select's value is changed, its value is passed to an invoked function updateDisplay() as a parameter.

    - -
    var verseChoose = document.querySelector('select');
    -var poemDisplay = document.querySelector('pre');
    -
    -verseChoose.onchange = function() {
    -  var verse = verseChoose.value;
    -  updateDisplay(verse);
    -};
    -
  4. -
  5. -

    Let's define our updateDisplay() function. First of all, put the following beneath your previous code block — this is the empty shell of the function:

    - -
    function updateDisplay(verse) {
    -
    -};
    -
  6. -
  7. -

    We'll start our function by constructing a relative URL pointing to the text file we want to load, as we'll need it later. The value of the {{htmlelement("select")}} element at any time is the same as the text inside the selected {{htmlelement("option")}} (unless you specify a different value in a value attribute) — so for example "Verse 1". The corresponding verse text file is "verse1.txt", and is in the same directory as the HTML file, therefore just the file name will do.

    - -

    However, web servers tend to be case sensitive, and the file name doesn't have a space in it. To convert "Verse 1" to "verse1.txt" we need to convert the V to lower case, remove the space, and add .txt on the end. This can be done with {{jsxref("String.replace", "replace()")}}, {{jsxref("String.toLowerCase", "toLowerCase()")}}, and simple string concatenation. Add the following lines inside your updateDisplay() function:

    - -
    verse = verse.replace(" ", "");
    -verse = verse.toLowerCase();
    -var url = verse + '.txt';
    -
  8. -
  9. -

    To begin creating an XHR request, you need to create a new request object using the {{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}} constructor. You can call this object anything you like, but we'll call it request to keep things simple. Add the following below your previous lines:

    - -
    var request = new XMLHttpRequest();
    -
  10. -
  11. -

    Next, you need to use the {{domxref("XMLHttpRequest.open","open()")}} method to specify what HTTP request method to use to request the resource from the network, and what its URL is. We'll just use the GET method here and set the URL as our url variable. Add this below your previous line:

    - -
    request.open('GET', url);
    -
  12. -
  13. -

    Next, we'll set the type of response we are expecting — which is defined by the request's {{domxref("XMLHttpRequest.responseType", "responseType")}} property — as text. This isn't strictly necessary here — XHR returns text by default — but it is a good idea to get into the habit of setting this in case you want to fetch other types of data in the future. Add this next:

    - -
    request.responseType = 'text';
    -
  14. -
  15. -

    Fetching a resource from the network is an {{glossary("asynchronous")}} operation, meaning that you have to wait for that operation to complete (e.g., the resource is returned from the network) before you can do anything with that response, otherwise, an error will be thrown. XHR allows you to handle this using its {{domxref("XMLHttpRequest.onload", "onload")}} event handler — this is run when the {{event("load")}} event fires (when the response has returned). When this has occurred, the response data will be available in the response property of the XHR request object.

    - -

    Add the following below your last addition. You'll see that inside the onload event handler we are setting the textContent of the poemDisplay (the {{htmlelement("pre")}} element) to the value of the {{domxref("XMLHttpRequest.response", "request.response")}} property.

    - -
    request.onload = function() {
    -  poemDisplay.textContent = request.response;
    -};
    -
  16. -
  17. -

    The above is all set up for the XHR request — it won't actually run until we tell it to, which is done using the {{domxref("XMLHttpRequest.send","send()")}} method. Add the following below your previous addition to complete the function:

    - -
    request.send();
    -
  18. -
  19. -

    One problem with the example as it stands is that it won't show any of the poem when it first loads. To fix this, add the following two lines at the bottom of your code (just above the closing </script> tag) to load verse 1 by default, and make sure the {{htmlelement("select")}} element always shows the correct value:

    - -
    updateDisplay('Verse 1');
    -verseChoose.value = 'Verse 1';
    -
  20. -
- -

Serving your example from a server

- -

Some browsers (including Chrome) will not run XHR requests if you just run the example from a local file. This is because of security restrictions (for more on web security, read Website security).

- -

To get around this, we need to test the example by running it through a local web server. To find out how to do this, read How do you set up a local testing server?

- -

Fetch

- -

The Fetch API is basically a modern replacement for XHR; it was introduced in browsers recently to make asynchronous HTTP requests easier to do in JavaScript, both for developers and other APIs that build on top of Fetch.

- -

Let's convert the last example to use Fetch instead.

- -
    -
  1. -

    Make a copy of your previous finished example directory. (If you didn't work through the previous exercise, create a new directory and inside it make copies of xhr-basic.html and the four text files — verse1.txt, verse2.txt, verse3.txt, and verse4.txt.)

    -
  2. -
  3. -

    Inside the updateDisplay() function, find the XHR code:

    - -
    var request = new XMLHttpRequest();
    -request.open('GET', url);
    -request.responseType = 'text';
    -
    -request.onload = function() {
    -  poemDisplay.textContent = request.response;
    -};
    -
    -request.send();
    -
  4. -
  5. -

    Replace all the XHR code with this:

    - -
    fetch(url).then(function(response) {
    -  response.text().then(function(text) {
    -    poemDisplay.textContent = text;
    -  });
    -});
    -
  6. -
  7. -

    Load the example in your browser (running it through a web server) and it should work just the same as the XHR version, provided you are running a modern browser.

    -
  8. -
- -

So what is going on in the Fetch code?

- -

First of all, we invoke the {{domxref("WorkerOrWindowGlobalScope.fetch()","fetch()")}} method, passing it the URL of the resource we want to fetch. This is the modern equivalent of {{domxref("XMLHttpRequest.open","request.open()")}} in XHR, plus you don't need any equivalent to .send().

- -

After that, you can see the {{jsxref("Promise.then",".then()")}} method chained onto the end of fetch() — this method is a part of {{jsxref("Promise","Promises")}}, a modern JavaScript feature for performing asynchronous operations. fetch() returns a promise, which resolves to the response sent back from the server — we use .then() to run some follow-up code after the promise resolves, which is the function we've defined inside it. This is the equivalent of the onload event handler in the XHR version.

- -

This function is automatically given the response from the server as a parameter when the fetch() promise resolves. Inside the function we grab the response and run its {{domxref("Body.text","text()")}} method, which basically returns the response as raw text. This is the equivalent of request.responseType = 'text' in the XHR version.

- -

You'll see that text() also returns a promise, so we chain another .then() onto it, inside of which we define a function to receive the raw text that the text() promise resolves to.

- -

Inside the inner promise's function, we do much the same as we did in the XHR version — set the {{htmlelement("pre")}} element's text content to the text value.

- -

Aside on promises

- -

Promises are a bit confusing the first time you meet them, but don't worry too much about this for now. You'll get used to them after a while, especially as you learn more about modern JavaScript APIs — most of the newer ones are heavily based on promises.

- -

Let's look at the promise structure from above again to see if we can make some more sense of it:

- -
fetch(url).then(function(response) {
-  response.text().then(function(text) {
-    poemDisplay.textContent = text;
-  });
-});
- -

The first line is saying "fetch the resource located at URL" (fetch(url)) and "then run the specified function when the promise resolves" (.then(function() { ... })). "Resolve" means "finish performing the specified operation at some point in the future". The specified operation, in this case, is to fetch a resource from a specified URL (using an HTTP request), and return the response for us to do something with.

- -

Effectively, the function passed into then() is a chunk of code that won't run immediately. Instead, it will run at some point in the future when the response has been returned. Note that you could also choose to store your promise in a variable and chain {{jsxref("Promise.then",".then()")}} onto that instead. The code below would do the same thing:

- -
var myFetch = fetch(url);
-
-myFetch.then(function(response) {
-  response.text().then(function(text) {
-    poemDisplay.textContent = text;
-  });
-});
- -

Because the fetch() method returns a promise that resolves to the HTTP response, any function you define inside a .then() chained onto the end of it will automatically be given the response as a parameter. You can call the parameter anything you like — the below example would still work:

- -
fetch(url).then(function(dogBiscuits) {
-  dogBiscuits.text().then(function(text) {
-    poemDisplay.textContent = text;
-  });
-});
- -

But it makes more sense to call the parameter something that describes its contents.

- -

Now let's focus just on the function:

- -
function(response) {
-  response.text().then(function(text) {
-    poemDisplay.textContent = text;
-  });
-}
- -

The response object has a method {{domxref("Body.text","text()")}} that takes the raw data contained in the response body and turns it into plain text — the format we want it in. It also returns a promise (which resolves to the resulting text string), so here we use another {{jsxref("Promise.then",".then()")}}, inside of which we define another function that dictates what we want to do with that text string. We are just setting the textContent property of our poem's {{htmlelement("pre")}} element to equal the text string, so this works out pretty simple.

- -

It is also worth noting that you can directly chain multiple promise blocks (.then() blocks, but there are other types too) onto the end of one another, passing the result of each block to the next block as you travel down the chain. This makes promises very powerful.

- -

The following block does the same thing as our original example, but is written in a different style:

- -
fetch(url).then(function(response) {
-  return response.text()
-}).then(function(text) {
-  poemDisplay.textContent = text;
-});
- -

Many developers like this style better, as it is flatter and arguably easier to read for longer promise chains — each subsequent promise comes after the previous one, rather than being inside the previous one (which can get unwieldy). The only other difference is that we've had to include a return statement in front of response.text(), to get it to pass its result on to the next link in the chain.

- -

Which mechanism should you use?

- -

This really depends on what project you are working on. XHR has been around for a long time now and has very good cross-browser support. Fetch and Promises, on the other hand, are a more recent addition to the web platform, although they're supported well across the browser landscape, with the exception of Internet Explorer.

- -

If you need to support older browsers, then an XHR solution might be preferable. If however you are working on a more progressive project and aren't as worried about older browsers, then Fetch could be a good choice.

- -

You should really learn both — Fetch will become more popular as Internet Explorer declines in usage (IE is no longer being developed, in favor of Microsoft's new Edge browser), but you might need XHR for a while yet.

- -

A more complex example

- -

To round off the article, we'll look at a slightly more complex example that shows some more interesting uses of Fetch. We have created a sample site called The Can Store — it's a fictional supermarket that only sells canned goods. You can find this example live on GitHub, and see the source code.

- -

A fake ecommerce site showing search options in the left hand column, and product search results in the right hand column.

- -

By default, the site displays all the products, but you can use the form controls in the left hand column to filter them by category, or search term, or both.

- -

There is quite a lot of complex code that deals with filtering the products by category and search terms, manipulating strings so the data displays correctly in the UI, etc. We won't discuss all of it in the article, but you can find extensive comments in the code (see can-script.js).

- -

We will however explain the Fetch code.

- -

The first block that uses Fetch can be found at the start of the JavaScript:

- -
fetch('products.json').then(function(response) {
-  return response.json();
-}).then(function(json) {
-  products = json;
-  initialize();
-}).catch(function(err) {
-  console.log('Fetch problem: ' + err.message);
-});
- -

The fetch() function returns a promise. If this completes successfully, the function inside the first .then() block contains the response returned from the network.

- -

Inside this function we run {{domxref("Body.json","json()")}} on the response, not {{domxref("Body.text","text()")}}, as we want to return our response as structured JSON data, not plain text.

- -

Next, we chain another .then() onto the end of our first one, the success function that contains the json returned from the response.json() promise. We set this to be the value of the products global object, then run initialize(), which starts the process of displaying all the products in the user interface.

- -

To handle errors, we chain a .catch() block onto the end of the chain. This runs if the promise fails for some reason. Inside it, we include a function that is passed as a parameter, an error object. This error object can be used to report the nature of the error that has occurred, in this case we do it with a simple console.log().

- -

However, a complete website would handle this error more gracefully by displaying a message on the user's screen and perhaps offering options to remedy the situation, but we don't need anything more than a simple console.log().

- -

You can test the fail case yourself:

- -
    -
  1. Make a local copy of the example files (download and unpack the can-store ZIP file).
  2. -
  3. Run the code through a web server (as described above, in {{anch("Serving your example from a server")}}).
  4. -
  5. Modify the path to the file being fetched, to something like 'produc.json' (make sure it is misspelled).
  6. -
  7. Now load the index file in your browser (via localhost:8000) and look in your browser developer console. You'll see a message similar to "Network request for products.json failed with response 404: File not found".
  8. -
- -

The second Fetch block can be found inside the fetchBlob() function:

- -
fetch(url).then(function(response) {
-    return response.blob();
-}).then(function(blob) {
-  // Convert the blob to an object URL — this is basically an temporary internal URL
-  // that points to an object stored inside the browser
-  var objectURL = URL.createObjectURL(blob);
-  // invoke showProduct
-  showProduct(objectURL, product);
-});
- -

This works in much the same way as the previous one, except that instead of using {{domxref("Body.json","json()")}}, we use {{domxref("Body.blob","blob()")}}. In this case we want to return our response as an image file, and the data format we use for that is Blob (the term is an abbreviation of "Binary Large Object" and can basically be used to represent large file-like objects, such as images or video files).

- -

Once we've successfully received our blob, we create an object URL out of it using {{domxref("URL.createObjectURL()", "createObjectURL()")}}. This returns a temporary internal URL that points to an object referenced inside the browser. These are not very readable, but you can see what one looks like by opening up the Can Store app, Ctrl-/Right-clicking on an image, and selecting the "View image" option (which might vary slightly depending on what browser you are using). The object URL will be visible inside the address bar, and should be something like this:

- -
blob:http://localhost:7800/9b75250e-5279-e249-884f-d03eb1fd84f4
- -

Challenge: An XHR version of the Can Store

- -

We'd like you to try converting the Fetch version of the app to use XHR as a useful bit of practice. Take a copy of the ZIP file, and try modifying the JavaScript as appropriate.

- -

Some helpful hints:

- - - -
-

Note: If you have trouble with this, feel free to check your code against the finished version on GitHub (see the source here, and also see it running live).

-
- -

Summary

- -

This article shows how to start working with both XHR and Fetch to fetch data from the server.

- -

See also

- -

There are however a lot of different subjects discussed in this article, which has only really scratched the surface. For a lot more detail on these subjects, try the following articles:

- - - -
{{PreviousMenuNext("Learn/JavaScript/Client-side_web_APIs/Manipulating_documents", "Learn/JavaScript/Client-side_web_APIs/Third_party_APIs", "Learn/JavaScript/Client-side_web_APIs")}}
- -
-

In this module

- - -
diff --git a/files/es/learn/server-side/express_nodejs/mongoose/index.html b/files/es/learn/server-side/express_nodejs/mongoose/index.html deleted file mode 100644 index f5701c468a..0000000000 --- a/files/es/learn/server-side/express_nodejs/mongoose/index.html +++ /dev/null @@ -1,801 +0,0 @@ ---- -title: 'Express Tutorial 3: Utilizando bases de datos (con Mongoose)' -slug: Learn/Server-side/Express_Nodejs/mongoose -translation_of: Learn/Server-side/Express_Nodejs/mongoose ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}
- -

Este artículo introduce brevemente las bases de datos así como su uso en aplicaciones Node/Express. Despues, profundiza en el uso específico de Mongoose en el proyecto LocalLibrary. Explica como se declaran y utilizan los esquemas modelo-objeto, los principales campos de datos y su validación básica. También muestra brevemente algunas de las muchas formas para acceder y modificar los datos.

- - - - - - - - - - - - -
PrerequisitosExpress Tutorial 2: Creando un esqueleto web
Objetivo:Ser capaz de crear, diseñar y utilizar bases de datos en Node/Express utilizando Mongoose
- -

Overview

- -

Library staff will use the Local Library website to store information about books and borrowers, while library members will use it to browse and search for books, find out whether there are any copies available, and then reserve or borrow them. In order to store and retrieve information efficiently, we will store it in a database.

- -

Las aplicaciones Express pueden utilizar diferentes bases de datos, y existen diferentes aproximaciones que se pueden utilizar para realizar operaciones CRUD (Create, Read, Update and Delete). Este tutorial proporciona una vista general sobre algunas de las opciones disponibles, para a continuación mostrar en detalle los mecanismos elegidos en particular.

- -

What databases can I use?

- -

Express apps can use any database supported by Node (Express itself doesn't define any specific additional behaviour/requirements for database management). There are many popular options, including PostgreSQL, MySQL, Redis, SQLite, and MongoDB.

- -

When choosing a database, you should consider things like time-to-productivity/learning curve, performance, ease of replication/backup, cost, community support, etc. While there is no single "best" database, almost any of the popular solutions should be more than acceptable for a small-to-medium-sized site like our Local Library.

- -

For more information on the options see: Database integration (Express docs).

- -

What is the best way to interact with a database?

- -

There are two approaches for interacting with a database: 

- - - -

The very best performance can be gained by using SQL, or whatever query language is supported by the database. ODM's are often slower because they use translation code to map between objects and the database format, which may not use the most efficient database queries (this is particularly true if the ODM supports different database backends, and must make greater compromises in terms of what database features are supported).

- -

The benefit of using an ORM is that programmers can continue to think in terms of JavaScript objects rather than database semantics — this is particularly true if you need to work with different databases (on either the same or different websites). They also provide an obvious place to perform validation and checking of data.

- -
-

Tip:  Using ODM/ORMs often results in lower costs for development and maintenance! Unless you're very familiar with the native query language or performance is paramount, you should strongly consider using an ODM.

-
- -

What ORM/ODM should I use?

- -

There are many ODM/ORM solutions available on the NPM package manager site (check out the odm and orm tags for a subset!).

- -

A few solutions that were popular at the time of writing are:

- - - -

As a general rule you should consider both the features provided and the "community activity" (downloads, contributions, bug reports, quality of documentation, etc.) when selecting a solution. At time of writing Mongoose is by far the most popular ORM, and is a reasonable choice if you're using MongoDB for your database.

- -

Using Mongoose and MongoDb for the LocalLibrary

- -

For the Local Library example (and the rest of this topic) we're going to use the Mongoose ODM to access our library data. Mongoose acts as a front end to MongoDB, an open source NoSQL database that uses a document-oriented data model. A “collection” of “documents”, in a MongoDB database, is analogous to a “table” of “rows” in a relational database.

- -

This ODM and database combination is extremely popular in the Node community, partially because the document storage and query system looks very much like JSON, and is hence familiar to JavaScript developers.

- -
-

Tip: You don't need to know MongoDB in order to use Mongoose, although parts of the Mongoose documentation are easier to use and understand if you are already familiar with MongoDB.

-
- -

The rest of this tutorial shows how to define and access the Mongoose schema and models for the LocalLibrary website example.

- -

Designing the LocalLibrary models

- -

Before you jump in and start coding the models, it's worth taking a few minutes to think about what data we need to store and the relationships between the different objects.

- -

We know that we need to store information about books (title, summary, author, genre, ISBN) and that we might have multiple copies available (with globally unique ids, availability statuses, etc.). We might need to store more information about the author than just their name, and there might be multiple authors with the same or similar names. We want to be able to sort information based on book title, author, genre, and category.

- -

When designing your models it makes sense to have separate models for every "object" (group of related information). In this case the obvious objects are books, book instances, and authors.

- -

You might also want to use models to represent selection-list options (e.g. like a drop down list of choices), rather than hard coding the choices into the website itself — this is recommended when all the options aren't known up front or may change. The obvious candidate for a model of this type is the book genre (e.g. Science Fiction, French Poetry, etc.)

- -

Once we've decided on our models and fields, we need to think about the relationships between them.

- -

With that in mind, the UML association diagram below shows the models we'll define in this case (as boxes). As discussed above, we've created models for book (the generic details of the book), book instance (status of specific physical copies of the book available in the system), and author. We have also decided to have a model for genre, so that values can be created dynamically. We've decided not to have a model for the BookInstance:status — we will hard code the acceptable values because we don't expect these to change. Within each of the boxes you can see the model name, the field names and types, and also the methods and their return types.

- -

The diagram also shows the relationships between the models, including their multiplicities. The multiplicities are the numbers on the diagram showing the numbers (maximum and minimum) of each model that may be present in the relationship. For example, the connecting line between the boxes shows that Book and a Genre are related. The numbers close to the Book model show that a Genre must have zero or more Book (as many as you like), while the numbers on the other end of the line next to the Genre show that it can have zero or more associated genre.

- -
-

Note: As discussed in our Mongoose primer below it is often better to have the field that defines the relationship between the documents/models in just one model (you can still find the reverse relationship by searching for the associated _id in the other model). Below we have chosen to define the relationship between Book/Genre and Book/Author in the Book schema, and the relationship between the Book/BookInstance in the BookInstance Schema. This choice was somewhat arbitrary — we could equally well have had the field in the other schema.

-
- -

Mongoose Library Model  with correct cardinality

- -
-

Note: The next section provides a basic primer explaining how models are defined and used. As you read it, consider how we will construct each of the models in the diagram above.

-
- -

Mongoose primer

- -

This section provides an overview of how to connect Mongoose to a MongoDB database, how to define a schema and a model, and how to make basic queries. 

- -
-

Note: This primer is "heavily influenced" by the Mongoose quick start on npm and the official documentation.

-
- -

Installing Mongoose and MongoDB

- -

Mongoose is installed in your project (package.json) like any other dependency — using NPM. To install it, use the following command inside your project folder:

- -
npm install mongoose
-
- -

Installing Mongoose adds all its dependencies, including the MongoDB database driver, but it does not install MongoDB itself. If you want to install a MongoDB server then you can download installers from here for various operating systems and install it locally. You can also use cloud-based MongoDB instances.

- -
-

Note: For this tutorial we'll be using the mLab cloud-based database as a service sandbox tier to provide the database. This is suitable for development, and makes sense for the tutorial because it makes "installation" operating system independent (database-as-a-service is also one approach you might well use for your production database).

-
- -

Connecting to MongoDB

- -

Mongoose requires a connection to a MongoDB database. You can require() and connect to a locally hosted database with mongoose.connect(), as shown below.

- -
//Import the mongoose module
-var mongoose = require('mongoose');
-
-//Set up default mongoose connection
-var mongoDB = 'mongodb://127.0.0.1/my_database';
-mongoose.connect(mongoDB);
-// Get Mongoose to use the global promise library
-mongoose.Promise = global.Promise;
-//Get the default connection
-var db = mongoose.connection;
-
-//Bind connection to error event (to get notification of connection errors)
-db.on('error', console.error.bind(console, 'MongoDB connection error:'));
- -

You can get the default Connection object with mongoose.connection. Once connected, the open event is fired on the Connection instance.

- -
-

Tip: If you need to create additional connections you can use mongoose.createConnection(). This takes the same form of database URI (with host, database, port, options etc.) as connect() and returns a Connection object).

-
- -

Defining and creating models

- -

Models are defined using the Schema interface. The Schema allows you to define the fields stored in each document along with their validation requirements and default values. In addition, you can define static and instance helper methods to make it easier to work with your data types, and also virtual properties that you can use like any other field, but which aren't actually stored in the database (we'll discuss a bit further below).

- -

Schemas are then "compiled" into models using the mongoose.model() method. Once you have a model you can use it to find, create, update, and delete objects of the given type.

- -
-

Note: Each model maps to a collection of documents in the MongoDB database. The documents will contain the fields/schema types defined in the model Schema.

-
- -

Defining schemas

- -

The code fragment below shows how you might define a simple schema. First you require() mongoose, then use the Schema constructor to create a new schema instance, defining the various fields inside it in the constructor's object parameter.

- -
//Require Mongoose
-var mongoose = require('mongoose');
-
-//Define a schema
-var Schema = mongoose.Schema;
-
-var SomeModelSchema = new Schema({
-    a_string: String,
-    a_date: Date
-});
-
- -

In the case above we just have two fields, a string and a date. In the next sections we will show some of the other field types, validation, and other methods.

- -

Creating a model

- -

Models are created from schemas using the mongoose.model() method:

- -
// Define schema
-var Schema = mongoose.Schema;
-
-var SomeModelSchema = new Schema({
-    a_string: String,
-    a_date: Date
-});
-
-// Compile model from schema
-var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
- -

The first argument is the singular name of the collection that will be created for your model (Mongoose will create the database collection for the above model SomeModel above), and the second argument is the schema you want to use in creating the model.

- -
-

Note: Once you've defined your model classes you can use them to create, update, or delete records, and to run queries to get all records or particular subsets of records. We'll show you how to do this in the Using models section, and when we create our views.

-
- -

Tipos de esquema (campos)

- -

Un esquema puede tener un número de campos arbitrario  — cada uno representa un campo en los documentos almacenados en MongoDB. A continuación se muestra un ejemplo de esquema con varios de los tipos de campos más comunes y cómo se declaran.

- -
var schema = new Schema(
-{
-  name: String,
-  binary: Buffer,
-  living: Boolean,
-  updated: { type: Date, default: Date.now },
-  age: { type: Number, min: 18, max: 65, required: true },
-  mixed: Schema.Types.Mixed,
-  _someId: Schema.Types.ObjectId,
-  array: [],
-  ofString: [String], // You can also have an array of each of the other types too.
-  nested: { stuff: { type: String, lowercase: true, trim: true } }
-})
- -

Most of the SchemaTypes (the descriptors after “type:” or after field names) are self explanatory. The exceptions are:

- - - -

The code also shows both ways of declaring a field:

- - - -

For more information about options see SchemaTypes (Mongoose docs).

- -

Validation

- -

Mongoose provides built-in and custom validators, and synchronous and asynchronous validators. It allows you to specify both the acceptable range or values and the error message for validation failure in all cases.

- -

The built-in validators include:

- - - -

The example below (slightly modified from the Mongoose documents) shows how you can specify some of the validator types and error messages:

- -

-    var breakfastSchema = new Schema({
-      eggs: {
-        type: Number,
-        min: [6, 'Too few eggs'],
-        max: 12,
-        required: [true, 'Why no eggs?']
-      },
-      drink: {
-        type: String,
-        enum: ['Coffee', 'Tea', 'Water',]
-      }
-    });
-
- -

For complete information on field validation see Validation (Mongoose docs).

- -

Virtual properties

- -

Virtual properties are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters are useful for de-composing a single value into multiple values for storage. The example in the documentation constructs (and deconstructs) a full name virtual property from a first and last name field, which is easier and cleaner than constructing a full name every time one is used in a template.

- -
-

Note: We will use a virtual property in the library to define a unique URL for each model record using a path and the record's _id value.

-
- -

For more information see Virtuals (Mongoose documentation).

- -

Methods and query helpers

- -

A schema can also have instance methods, static methods, and query helpers. The instance and static methods are similar, but with the obvious difference that an instance method is associated with a particular record and has access to the current object. Query helpers allow you to extend mongoose's chainable query builder API (for example, allowing you to add a query "byName" in addition to the find(), findOne() and findById() methods).

- -

Using models

- -

Once you've created a schema you can use it to create models. The model represents a collection of documents in the database that you can search, while the model's instances represent individual documents that you can save and retrieve.

- -

We provide a brief overview below. For more information see: Models (Mongoose docs).

- -

Creating and modifying documents

- -

To create a record you can define an instance of the model and then call save(). The examples below assume SomeModel is a model (with a single field "name") that we have created from our schema.

- -
// Create an instance of model SomeModel
-var awesome_instance = new SomeModel({ name: 'awesome' });
-
-// Save the new model instance, passing a callback
-awesome_instance.save(function (err) {
-  if (err) return handleError(err);
-  // saved!
-});
-
- -

Creation of records (along with updates, deletes, and queries) are asynchronous operations — you supply a callback that is called when the operation completes. The API uses the error-first argument convention, so the first argument for the callback will always be an error value (or null). If the API returns some result, this will be provided as the second argument.

- -

You can also use create() to define the model instance at the same time as you save it. The callback will return an error for the first argument and the newly-created model instance for the second argument.

- -
SomeModel.create({ name: 'also_awesome' }, function (err, awesome_instance) {
-  if (err) return handleError(err);
-  // saved!
-});
- -

Every model has an associated connection (this will be the default connection when you use mongoose.model()). You create a new connection and call .model() on it to create the documents on a different database.

- -

You can access the fields in this new record using the dot syntax, and change the values. You have to call save() or update() to store modified values back to the database.

- -
// Access model field values using dot notation
-console.log(awesome_instance.name); //should log 'also_awesome'
-
-// Change record by modifying the fields, then calling save().
-awesome_instance.name="New cool name";
-awesome_instance.save(function (err) {
-   if (err) return handleError(err); // saved!
-   });
-
- -

Searching for records

- -

You can search for records using query methods, specifying the query conditions as a JSON document. The code fragment below shows how you might find all athletes in a database that play tennis, returning just the fields for athlete name and age. Here we just specify one matching field (sport) but you can add more criteria, specify regular expression criteria, or remove the conditions altogether to return all athletes.

- -
var Athlete = mongoose.model('Athlete', yourSchema);
-
-// find all athletes who play tennis, selecting the 'name' and 'age' fields
-Athlete.find({ 'sport': 'Tennis' }, 'name age', function (err, athletes) {
-  if (err) return handleError(err);
-  // 'athletes' contains the list of athletes that match the criteria.
-})
- -

If you specify a callback, as shown above, the query will execute immediately. The callback will be invoked when the search completes.

- -
-

Note: All callbacks in Mongoose use the pattern callback(error, result). If an error occurs executing the query, the error parameter will contain an error document, and result will be null. If the query is successful, the error parameter will be null, and the result will be populated with the results of the query.

-
- -

If you don't specify a callback then the API will return a variable of type Query. You can use this query object to build up your query and then execute it (with a callback) later using the exec() method.

- -
// find all athletes that play tennis
-var query = Athlete.find({ 'sport': 'Tennis' });
-
-// selecting the 'name' and 'age' fields
-query.select('name age');
-
-// limit our results to 5 items
-query.limit(5);
-
-// sort by age
-query.sort({ age: -1 });
-
-// execute the query at a later time
-query.exec(function (err, athletes) {
-  if (err) return handleError(err);
-  // athletes contains an ordered list of 5 athletes who play Tennis
-})
- -

Above we've defined the query conditions in the find() method. We can also do this using a where() function, and we can chain all the parts of our query together using the dot operator (.) rather than adding them separately. The code fragment below is the same as our query above, with an additional condition for the age.

- -
Athlete.
-  find().
-  where('sport').equals('Tennis').
-  where('age').gt(17).lt(50).  //Additional where query
-  limit(5).
-  sort({ age: -1 }).
-  select('name age').
-  exec(callback); // where callback is the name of our callback function.
- -

The find() method gets all matching records, but often you just want to get one match. The following methods query for a single record:

- - - -
-

Note: There is also a count() method that you can use to get the number of items that match conditions. This is useful if you want to perform a count without actually fetching the records.

-
- -

There is a lot more you can do with queries. For more information see: Queries (Mongoose docs).

- - - -

You can create references from one document/model instance to another using the ObjectId schema field, or from one document to many using an array of ObjectIds. The field stores the id of the related model. If you need the actual content of the associated document, you can use the populate() method in a query to replace the id with the actual data.

- -

For example, the following schema defines authors and stories. Each author can have multiple stories, which we represent as an array of ObjectId. Each story can have a single author. The "ref" (highlighted in bold below) tells the schema which model can be assigned to this field.

- -
var mongoose = require('mongoose')
-  , Schema = mongoose.Schema
-
-var authorSchema = Schema({
-  name    : String,
-  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
-});
-
-var storySchema = Schema({
-  author : { type: Schema.Types.ObjectId, ref: 'Author' },
-  title    : String
-});
-
-var Story  = mongoose.model('Story', storySchema);
-var Author = mongoose.model('Author', authorSchema);
- -

We can save our references to the related document by assigning the _id value. Below we create an author, then a story, and assign the author id to our stories author field.

- -
var bob = new Author({ name: 'Bob Smith' });
-
-bob.save(function (err) {
-  if (err) return handleError(err);
-
-  //Bob now exists, so lets create a story
-  var story = new Story({
-    title: "Bob goes sledding",
-    author: bob._id    // assign the _id from the our author Bob. This ID is created by default!
-  });
-
-  story.save(function (err) {
-    if (err) return handleError(err);
-    // Bob now has his story
-  });
-});
- -

Our story document now has an author referenced by the author document's ID. In order to get the author information in our story results we use populate(), as shown below.

- -
Story
-.findOne({ title: 'Bob goes sledding' })
-.populate('author') //This populates the author id with actual author information!
-.exec(function (err, story) {
-  if (err) return handleError(err);
-  console.log('The author is %s', story.author.name);
-  // prints "The author is Bob Smith"
-});
- -
-

Note: Astute readers will have noted that we added an author to our story, but we didn't do anything to add our story to our author's stories array. How then can we get all stories by a particular author? One way would be to add our author to the stories array, but this would result in us having two places where the information relating authors and stories needs to be maintained.

- -

A better way is to get the _id of our author, then use find() to search for this in the author field across all stories.

- -
Story
-.find({ author : bob._id })
-.exec(function (err, stories) {
-  if (err) return handleError(err);
-  // returns all stories that have Bob's id as their author.
-});
-
-
- -

This is almost everything you need to know about working with related items for this tutorial. For more detailed information see Population (Mongoose docs).

- -

One schema/model per file

- -

While you can create schemas and models using any file structure you like, we highly recommend defining each model schema in its own module (file), exporting the method to create the model. This is shown below:

- -
// File: ./models/somemodel.js
-
-//Require Mongoose
-var mongoose = require('mongoose');
-
-//Define a schema
-var Schema = mongoose.Schema;
-
-var SomeModelSchema = new Schema({
-    a_string          : String,
-    a_date            : Date,
-});
-
-//Export function to create "SomeModel" model class
-module.exports = mongoose.model('SomeModel', SomeModelSchema );
- -

You can then require and use the model immediately in other files. Below we show how you might use it to get all instances of the model.

- -
//Create a SomeModel model just by requiring the module
-var SomeModel = require('../models/somemodel')
-
-// Use the SomeModel object (model) to find all SomeModel records
-SomeModel.find(callback_function);
- -

Setting up the MongoDB database

- -

Now that we understand something of what Mongoose can do and how we want to design our models, it's time to start work on the LocalLibrary website. The very first thing we want to do is set up a MongoDb database that we can use to store our library data.

- -

For this tutorial we're going to use mLab's free cloud-hosted "sandbox" database. This database tier is not considered suitable for production websites because it has no redundancy, but it is great for development and prototyping. We're using it here because it is free and easy to set up, and because mLab is a popular database as a service vendor that you might reasonably choose for your production database (other popular choices at the time of writing include Compose, ScaleGrid and MongoDB Atlas).

- -
-

Note: If you prefer you can set up a MongoDb database locally by downloading and installing the appropriate binaries for your system. The rest of the instructions in this article would be similar, except for the database URL you would specify when connecting.

-
- -

You will first need to create an account with mLab (this is free, and just requires that you enter basic contact details and acknowledge their terms of service). 

- -

After logging in, you'll be taken to the home screen:

- -
    -
  1. Click Create New in the MongoDB Deployments section.
  2. -
  3. This will open the Cloud Provider Selection screen.
    - MLab - screen for new deployment
    - -
      -
    • Select the SANDBOX (Free) plan from the Plan Type section. 
    • -
    • Select any provider from the Cloud Provider section. Different providers offer different regions (displayed below the selected plan type).
    • -
    • Click the Continue button.
    • -
    -
  4. -
  5. This will open the Select Region screen. -

    Select new region screen

    - -
      -
    • -

      Select the region closest to you and then Continue.

      -
    • -
    -
  6. -
  7. -

    This will open the Final Details screen.
    - New deployment database name

    - -
      -
    • -

      Enter the name for the new database as local_library and then select Continue.

      -
    • -
    -
  8. -
  9. -

    This will open the Order Confirmation screen.
    - Order confirmation screen

    - -
      -
    • -

      Click Submit Order to create the database.

      -
    • -
    -
  10. -
  11. -

    You will be returned to the home screen. Click on the new database you just created to open its details screen. As you can see the database has no collections (data).
    - mLab - Database details screen
    -  
    - The URL that you need to use to access your database is displayed on the form above (shown for this database circled above). In order to use this you need to create a database user that you can specify in the URL.

    -
  12. -
  13. Click the Users tab and select the Add database user button.
  14. -
  15. Enter a username and password (twice), and then press Create. Do not select Make read only.
    -
  16. -
- -

You have now created the database, and have an URL (with username and password) that can be used to access it. This will look something like: mongodb://your_user_namer:your_password@ds119748.mlab.com:19748/local_library.

- -

Install Mongoose

- -

Open a command prompt and navigate to the directory where you created your skeleton Local Library website. Enter the following command to install Mongoose (and its dependencies) and add it to your package.json file, unless you have already done so when reading the Mongoose Primer above.

- -
npm install mongoose
-
- -

Connect to MongoDB

- -

Open /app.js (in the root of your project) and copy the following text below where you declare the Express application object (after the line var app = express();). Replace the database url string ('insert_your_database_url_here') with the location URL representing your own database (i.e. using the information from mLab).

- -
//Set up mongoose connection
-var mongoose = require('mongoose');
-var mongoDB = 'insert_your_database_url_here';
-mongoose.connect(mongoDB);
-mongoose.Promise = global.Promise;
-var db = mongoose.connection;
-db.on('error', console.error.bind(console, 'MongoDB connection error:'));
- -

As discussed in the Mongoose primer above, this code creates the default connection to the database and binds to the error event (so that errors will be printed to the console). 

- -

Defining the LocalLibrary Schema

- -

We will define a separate module for each model, as discussed above. Start by creating a folder for our models in the project root (/models) and then create separate files for each of the models:

- -
/express-locallibrary-tutorial  //the project root
-  /models
-    author.js
-    book.js
-    bookinstance.js
-    genre.js
-
- -

Author model

- -

Copy the Author schema code shown below and paste it into your ./models/author.js file. The scheme defines an author has having String SchemaTypes for the first and family names, that are required and have a maximum of 100 characters, and Date fields for the date of birth and death.

- -
var mongoose = require('mongoose');
-
-var Schema = mongoose.Schema;
-
-var AuthorSchema = new Schema(
-  {
-    first_name: {type: String, required: true, max: 100},
-    family_name: {type: String, required: true, max: 100},
-    date_of_birth: {type: Date},
-    date_of_death: {type: Date},
-  }
-);
-
-// Virtual for author's full name
-AuthorSchema
-.virtual('name')
-.get(function () {
-  return this.family_name + ', ' + this.first_name;
-});
-
-// Virtual for author's lifespan
-AuthorSchema
-.virtual('lifespan')
-.get(function () {
-  return (this.date_of_death.getYear() - this.date_of_birth.getYear()).toString();
-});
-
-// Virtual for author's URL
-AuthorSchema
-.virtual('url')
-.get(function () {
-  return '/catalog/author/' + this._id;
-});
-
-//Export model
-module.exports = mongoose.model('Author', AuthorSchema);
-
-
- -

We've also declared a virtual for the AuthorSchema named "url" that returns the absolute URL required to get a particular instance of the model — we'll use the property in our templates whenever we need to get a link to a particular author.

- -
-

Note: Declaring our URLs as a virtual in the schema is a good idea because then the URL for an item only ever needs to be changed in one place.
- At this point, a link using this URL wouldn't work, because we haven't got any routes handling code for individual model instances. We'll set those up in a later article!

-
- -

At the end of the module we export the model.

- -

Book model

- -

Copy the Book schema code shown below and paste it into your ./models/book.js file. Most of this is similar to the author model — we've declared a schema with a number of string fields and a virtual for getting the URL of specific book records, and we've exported the model.

- -
var mongoose = require('mongoose');
-
-var Schema = mongoose.Schema;
-
-var BookSchema = new Schema(
-  {
-    title: {type: String, required: true},
-    author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},
-    summary: {type: String, required: true},
-    isbn: {type: String, required: true},
-    genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]
-  }
-);
-
-// Virtual for book's URL
-BookSchema
-.virtual('url')
-.get(function () {
-  return '/catalog/book/' + this._id;
-});
-
-//Export model
-module.exports = mongoose.model('Book', BookSchema);
-
- -

The main difference here is that we've created two references to other models:

- - - -

BookInstance model

- -

Finally, copy the BookInstance schema code shown below and paste it into your ./models/bookinstance.js file. The BookInstance represents a specific copy of a book that someone might borrow, and includes information about whether the copy is available or on what date it is expected back, "imprint" or version details.

- -
var mongoose = require('mongoose');
-
-var Schema = mongoose.Schema;
-
-var BookInstanceSchema = new Schema(
-  {
-    book: { type: Schema.Types.ObjectId, ref: 'Book', required: true }, //reference to the associated book
-    imprint: {type: String, required: true},
-    status: {type: String, required: true, enum: ['Available', 'Maintenance', 'Loaned', 'Reserved'], default: 'Maintenance'},
-    due_back: {type: Date, default: Date.now}
-  }
-);
-
-// Virtual for bookinstance's URL
-BookInstanceSchema
-.virtual('url')
-.get(function () {
-  return '/catalog/bookinstance/' + this._id;
-});
-
-//Export model
-module.exports = mongoose.model('BookInstance', BookInstanceSchema);
- -

The new things we show here are the field options:

- - - -

Everything else should be familiar from our previous schema.

- -

Genre model - challenge!

- -

Open your ./models/genre.js file and create a schema for storing genres (the category of book, e.g. whether it is fiction or non-fiction, romance or military history, etc).

- -

The definition will be very similar to the other models:

- - - -

Testing — create some items

- -

That's it. We now have all models for the site set up!

- -

In order to test the models (and to create some example books and other items that we can use in our next articles) we'll now run an independent script to create items of each type:

- -
    -
  1. Download (or otherwise create) the file populatedb.js inside your express-locallibrary-tutorial directory (in the same level as package.json). - -
    -

    Note: You don't need to know how populatedb.js works; it just adds sample data into the database.

    -
    -
  2. -
  3. Enter the following commands in the project root to install the async module that is required by the script (we'll discuss this in later tutorials, ) -
    npm install async
    -
  4. -
  5. Run the script using node in your command prompt, passing in the URL of your MongoDB database (the same one you replaced the insert_your_database_url_here placeholder with, inside app.js earlier): -
    node populatedb <your mongodb url>​​​​
    -
  6. -
  7. The script should run through to completion, displaying items as it creates them in the terminal.
  8. -
- -
-

Tip: Go to your database on mLab. You should now be able to drill down into individual collections of Books, Authors, Genres and BookInstances, and check out individual documents.

-
- -

Summary

- -

In this article, we've learned a bit about databases and ORMs on Node/Express, and a lot about how Mongoose schema and models are defined. We then used this information to design and implement Book, BookInstance, Author and Genre models for the LocalLibrary website.

- -

Last of all we tested our models by creating a number of instances (using a standalone script). In the next article we'll look at creating some pages to display these objects.

- -

See also

- - - -

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html b/files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html deleted file mode 100644 index 3acb3d4039..0000000000 --- a/files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html +++ /dev/null @@ -1,295 +0,0 @@ ---- -title: Primeros pasos con Vue -slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started -translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started -original_slug: >- - Learn/Herramientas_y_pruebas/Lado-del-cliente_JavaScript_frameworks/Vue_primeros_pasos ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
- -

Ahora vamos a introducir Vue, el tercero de nuestros frameworks. En este articulo vamos a ver un poco del background de Vue, aprenderemos cómo instalarlo y a crear un nuevo proyecto, estudiar la estructura de alto nivel de todo el proyecto y un componente individual, sabremos como correr el proyecto localmente, y tenerlo preparado para empezar a construir nuestro ejemplo.

- - - - - - - - - - - - -
Pre-requisitos: -

Familiaridad con los motores de los lenguajes  HTML, CSS, y  JavaScript languages, conocimiento del terminal/command line.

- -

Los componentes Vue son escritos como una combinacion de objectos Javascript que administran los datos de la app y una sintaxis de plantilla basada en HTML que se enlaza con la estructura DOM subyacente. Para la instalación, y para usar algunas de las caracteristicas mas avanzadas de Vue (como Componentes de archivos simples o renderizado de funciones), vas a necesitar un terminar con node + npm instalados.

-
Objetivo:Configurar un entorno de desarrollo local de Vue, crear una app de inicio y entender los principios de su funcionamiento.
- -

Un Vue más claro

- -

Vue es un framework moderno de Javascript que proveé facilidades muy utiles para el mejoramiento progresivo- al contrario de otros frameworks, puedes usar Vue para mejorar un HTML exstente. Esto permite usar Vue como un remplazo agregado para una libreria como JQuery.

- -

Habiendo dicho esto, tambien puedes usar Vue para escribir completamente una aplicación de una sola página(SPAs).This allows you to create markup managed entirely by Vue, which can improve developer experience and performance when dealing with complex applications. It also allows you to take advantage of libraries for client-side routing and state management when you need to. Additionally, Vue takes a "middle ground" approach to tooling like client-side routing and state management. While the Vue core team maintains suggested libraries for these functions, they are not directly bundled into Vue. This allows you to select a different routing/state management library if they better fit your application.

- -

In addition to allowing you to progressively integrate Vue into your applications, Vue also provides a progressive approach to writing markup. Like most frameworks, Vue lets you create reusable blocks of markup via components. Most of the time, Vue components are written using a special HTML template syntax. When you need more control than the HTML syntax allows, you can write JSX or plain JavaScript functions to define your  components.

- -

As you work through this tutorial, you might want to keep the Vue guide and API documentation open in other tabs, so you can refer to them if you want more information on any sub topic.
- For a good (but potentially biased) comparison between Vue and many of the other frameworks, see Vue Docs: Comparison with Other Frameworks.

- -

Installation

- -

To use Vue in an existing site, you can drop one of the following <script> elements onto a page. This allows you to start using Vue on existing sites, which is why Vue prides itself on being a progressive framework. This is a great option when migrating an existing project using a library like JQuery to Vue. With this method, you can use a lot of the core features of Vue, such as the attributes, custom components, and data-management.

- - - -

However, this approach has some limitations. To build more complex apps, you’ll want to use the Vue NPM package. This will let you use advanced features of Vue and take advantage of bundlers like WebPack. To make building apps with Vue easier, there is a CLI to streamline the development process. To use the npm package & the CLI you will need:

- -
    -
  1. Node.js 8.11+ installed.
  2. -
  3. npm or yarn.
  4. -
- -
-

Note: If you don't have the above installed, find out more about installing npm and Node.js here.

-
- -

To install the CLI, run the following command in your terminal:

- -
npm install --global @vue/cli
- -

Or if you'd prefer to use yarn:

- -
yarn global add @vue/cli
- -

Once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run vue create <project-name>. The CLI will then give you a list of project configurations you can use. There are a few preset ones, and you can make your own. These options let you configure things like TypeScript, linting, vue-router, testing, and more.

- -

We’ll look at using this below.

- -

Initializing a new project

- -

To explore various features of Vue, we will be building up a sample todo list app. We'll begin by using the Vue CLI to create a new app framework to build our app into. Follow the steps below:

- -
    -
  1. In terminal, cd to where you'd like to create your sample app, then run vue create moz-todo-vue.
  2. -
  3. Use the arrow keys and Enter to select the "Manually select features" option.
  4. -
  5. The first menu you’ll be presented with allows you to choose which features you want to include in your project. Make sure that "Babel" and "Linter / Formatter" are selected. If they are not, use the arrow keys and the space bar to toggle them on. Once they are selected, press Enter to proceed.
  6. -
  7. Next you’ll select a config for the linter / formatter. Navigate to "Eslint with error prevention only" and hit Enter again. This will help us catch common errors, but not be overly opinionated.
  8. -
  9. Next you are asked to configure what kind of automated linting we want. Select "Lint on save". This will check for errors when we save a file inside the project. Hit Enter to continue.
  10. -
  11. Now, you will select how we want your config files to be managed. "In dedicated config files" will put your config settings for things like ESLint into their own, dedicated files. The other option, "In package.json", will put all of your config settings into the app's package.json file. Select "In dedicated config files" and push Enter.
  12. -
  13. Finally, you are asked if you want to save this as a preset for future options. This is entirely up to you. If you like these settings over the existing presets and want to use them again, type y , otherwise type n.
  14. -
- -

The CLI will now begin scaffolding out your project, and installing all of your dependencies.

- -

If you've never run the Vue CLI before, you'll get one more question — you'll be asked to choose a package manager. You can use the arrow keys to select which one you prefer. The Vue CLI will default to this package manager from now on. If you need to use a different package manager after this, you can pass in a flag --packageManager=<package-manager>, when you run vue create.  So if you wanted to create the moz-todo-vue project with npm and you'd previously chosen yarn, you’d run vue create moz-todo-vue --packageManager=npm.

- -
-

Note: We've not gone over all of the options here, but you can find more information on the CLI in the Vue docs.

-
- -

Project structure

- -

If everything went successfully, the CLI should have created a series of files and directories for your project. The most significant ones are as follows:

- - - -
-

Note: Depending on the options you select when creating a new project, there might be other directories present (for example, if you choose a router, you will also have a views directory).

-
- -

.vue files (single file components)

- -

Like in many front-end frameworks, components are a central part of building apps in Vue. These components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required. These small blocks can help you reason about and test your code.

- -

While some frameworks encourage you to separate your template, logic, and styling code into separate files, Vue takes the opposite approach. Using Single File Components, Vue lets you group your templates, corresponding script, and CSS all together in a single file ending in .vue. These files are processed by a JS build tool (such as Webpack), which means you can take advantage of build-time tooling in your project. This allows you to use tools like Babel, TypeScript, SCSS and more to create more sophisticated components.

- -

As a bonus, projects created with the Vue CLI are configured to use .vue files with Webpack out of the box. In fact, if you look inside the src folder in the project we created with the CLI, you'll see your first .vue file: App.vue.

- -

Let's explore this now.

- -

App.vue

- -

Open your App.vue file — you’ll see that it has three parts: <template>, <script>, and <style>, which contain the component’s template, scripting, and styling information. All Single File Components share this same basic structure.

- -

<template> contains all the markup structure and display logic of your component. Your template can contain any valid HTML, as well as some Vue-specific syntax that we'll cover later.

- -
-

Note: By setting the lang attribute on the <template> tag, you can use Pug template syntax instead of standard HTML — <template lang="pug">. We'll stick to standard HTML through this tutorial, but it is worth knowing that this is possible.

-
- -

<script> contains all of the non-display logic of your component. Most importantly, your <script> tag needs to have a default exported JS object. This object is where you locally register components, define component inputs (props), handle local state, define methods, and more. Your build step will process this object and transform it (with your template) into a Vue component with a render() function.

- -

In the case of App.vue, our default export sets the name of the component to app and registers the HelloWorld component by adding it into the components property. When you register a component in this way, you're registering it locally. Locally registered components can only be used inside the components that register them, so you need to import and register them in every component file that uses them. This can be useful for bundle splitting/tree shaking since not every page in your app necessarily needs every component.

- -
import HelloWorld from './components/HelloWorld.vue';
-
-export default {
-  name: 'app',
-  components: {
-    //You can register components locally here.
-    HelloWorld
-  }
-};
- -
-

Note: If you want to use TypeScript syntax, you need to set the lang attribute on the <script> tag to signify to the compiler that you're using TypeScript — <script lang="ts">.

-
- -

<style> is where you write your CSS for the component. If you add a scoped attribute — <style scoped> — Vue will scope the styles to the contents of your SFC. This works similar to CSS-in-JS solutions, but allows you to just write plain CSS.

- -
-

Note: If you select a CSS pre-processor when creating the project via the CLI, you can add a lang attribute to the <style> tag so that the contents can be processed by Webpack at build time. For example, <style lang="scss"> will allow you to use SCSS syntax in your styling information.

-
- -

Running the app locally

- -

The Vue CLI comes with a built-in development server. This allows you to run your app locally so you can test it easily without needing to configure a server yourself. The CLI adds a serve command to the project’s package.json file as an npm script, so you can easily run it.

- -

In your terminal, try running npm run serve (or yarn serve if you prefer yarn). Your terminal should output something like the following:

- -
INFO  Starting development server...
-98% after emitting CopyPlugin
-
- DONE  Compiled successfully in 18121ms
-
-  App running at:
-  - Local:   <http://localhost:8080/>
-  - Network: <http://192.168.1.9:8080/>
-
-  Note that the development build is not optimized.
-  To create a production build, run npm run build.
- -

If you navigate to the “local” address in a new browser tab (this should be something like http://localhost:8080 as stated above, but may vary based on your setup), you should see your app. Right now, it should contain a welcome message, a link to the Vue documentation, links to the plugins you added when you initialized the app with your CLI, and some other useful links to the Vue community and ecosystem.

- -

default vue app render, with vue logo, welcome message, and some documentation links

- -

Making a couple of changes

- -

Let's make our first change to the app — we’ll delete the Vue logo. Open the App.vue file, and delete the <img> element from the template section:

- -
<img alt="Vue logo" src="./assets/logo.png">
- -

If your server is still running, you should see the logo removed from the rendered site almost instantly. Let’s also remove the HelloWorld component from our template.

- -

First of all delete this line:

- -
<HelloWorld msg="Welcome to Your Vue.js App"/>
- -

If you save your App.vue file now, the rendered app will throw an error because we’ve registered the component but are not using it. We also need to remove the lines from inside the <script> element that import and register the component:

- -

Delete these lines now:

- -
import HelloWorld from './components/HelloWorld.vue'
- -
components: {
-  HelloWorld
-}
- -

Your rendered app should no longer show an error, just a blank page, as we currently have no visible content inside <template>.

- -

Let’s add a new <h1> inside <div id="app">. Since we’re going to be creating a todo list app below, let's set our header text to "To-Do List". Add it like so:

- -
<template>
-  <div id="app">
-    <h1>To-Do List</h1>
-  </div>
-</template>
- -

App.vue will now show our heading, as you'd expect.

- -

Summary

- -

Let's leave this here for now. We've learnt about some of the ideas behind Vue, created some scaffolding for our example app to live inside, inspected it, and made a few preliminary changes.

- -

With a basic introduction out of the way, we'll now go further and build up our sample app, a basic Todo list application that allows us to store a list of items, check them off when done, and filter the list by all, complete, and incomplete todos.

- -

In the next article we'll build our first custom component, and look at some important concepts such as passing props into it and saving its data state.

- -

{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}

- -

In this module

- - -- cgit v1.2.3-54-g00ecf