Vue.js Series Tutorial 1: Rendering, directives, events

Source: Internet
Author: User

Original: Intro-to-vue-1-rendering-directives-events

Translator: Nzbin

If I were to describe my experience using Vue in a sentence, I might say, "It's so sensible," or "It gives me the tools I need, and it doesn't interfere with my work." Every time I studied Vue, I was happy because it was meaningful and elegant.

The above is my introduction to Vue. The first time I studied Vue, I wanted this article. If you prefer a nonpartisan approach, check out Vue's easy-to-understand user guide.

Series Articles:
    1. Rendering, instructions, events (here you are!)
    2. Components, Props, Slots
    3. Vue-cli
    4. Vuex
    5. Animation

One thing I like about Vue is that it draws on the excellence of other frameworks and methodically combines them. Like what:

    • The virtual DOM with responsive components provides only the view layer, and props and class Redux state management are similar to React.
    • Conditional rendering and services are similar to Angular.
    • Inspired by polymer simplicity and performance, Vue offers similar patterns, such as HTML, styling, and JavaScript.

Vue has advantages over other frameworks: brevity, providing more semantic APIs, a little better than React, not using polyfill like polymer, and having a separate view compared to Angular.

I can also cite some examples, but you'd better read this comprehensive, community-driven article to compare other frameworks. This article is worth reading, but if you want to read the code first, you can skip it and read it later.

Let's go!

Or start with the example "Hello, world!." Run the following example:

<div id= "App" > {{text}} nice to meet vue.</div>
New Vue ({el: ' #app ', data: {   text: ' Hello world! '}});

If you are familiar with React, you will find that there are many similarities between the two. By mustache templates and using a variable, you can avoid using JavaScript in your content, but the difference is that we write HTML directly instead of JSX. Although JSX is easy to use, I don't have to take the time to class change className it, and so on. This will make the startup and operation lighter.

Now try the features of my favorite Vue: looping and conditional rendering.

Conditional rendering

If there is a set of elements, like the navigation bar, I intend to reuse. A reasonable approach is to put the dynamic updates in the array. Using normal JS (requires Babel), we will do this: Create an array and then create an empty string to hold <li> the elements that use the package, and then use the <ul> InnerHTML method to add the contents of the package to the DOM:

<div id= "Container" ></div>
Const ITEMS = [  ' thingie ',  ' another thingie ',  ' lots of stuff ',  ' yadda yadda '];function listofstuff () { C4/>let full_list = ";  for (Let i = 0; i < items.length; i++) {      full_list = full_list + ' <li> ${items[i]} </li> '  }  con St contain = document.queryselector (' #container ');  contain.innerhtml = ' <ul> ${full_list} </ul> ';     } Listofstuff ();

This method is feasible, but a bit troublesome. Now try the Vue v-for loop:

<div id= "App" >  <ul>    <li v-for= "item in Items" >      {{item}}    </li>  </ul></div>
Const APP4 = new Vue ({  el: ' #app ',  data: {    items: [      ' thingie ',      ' another thingie ',      ' lots of stuff ',      ' yadda yadda '  }});

Very concise. If you are familiar with Angular, you should not be unfamiliar with it. I found the way this conditional rendering is straightforward. If you need to update your content, it's easy to change it.

Another good way is to use V-model for dynamic binding. Try the following example:

<div id= "App" >  
New Vue ({  el: ' #app ',  data () {    return {      message: ' This was a good place to type things. '}}}  );

You will notice two points in this demo. First, you can type directly into the book and update the text dynamically. Vue v-model implements <textarea> and data binding through very convenient <p> .

Second, you might notice that we put the data in the function. In this case, it is not possible to do so. We can put it in an object just like the previous example. However, this approach can only be used in the Vue instance, as is the case in the program (so do not use this method in the component). It is possible to use this in a Vue instance, but we need to share the data in the subcomponents. It's a good idea to put the data in a function in the first place because we want each component to have its own state when using the component.

Instead of just simple input bindings, v-if you can even v-show replace them with elements that are v-show not destroying or rebuilding components, but are always in the DOM, switching visibility.

Vue provides a lot of instructions, and here are some of the instructions I use frequently. Many instructions have abbreviations, so I'll list them together. In the following tutorial, we mainly use instruction abbreviations, so it's a good idea to familiarize yourself with the table below.

name Abbreviations function Example
v-if, v-else-if, v-else None Conditional rendering <g v-if="flourish === ‘A‘"></g>
<g v-else-if="flourish === ‘B‘"></g>
<g v-else></g>
v-bind : Bind one or more attributes dynamically, or a component prop to an expression <div :style="{ background: color }"></div>
v-on @ Binding event listeners to elements <button @click="fnName"></button>
v-model None Create a two-way binding <textarea rows="5" v-model="message" maxlength="72"></textarea>
v-pre None Skip the original content compilation process to improve performance <div v-pre>{{ raw content with no methods}}</div>
v-once None Do not render <div class=”v-once”>Keep me from rerendering</div>
v-show None Displays or hides components/elements based on status, but is saved in the DOM and will not be destroyed (unlike v-if) <child v-show=”showComponent”></child>(Toggle visibility When showcomponent is true)

There are also very good event modifiers and other APIs

Ways to speed up development:

    • @mousemove.stopand the e.stopPropogation() same
    • @mousemove.preventSimilar toe.preventDefault()
    • @submit.preventPage is no longer reloaded on commit
    • @click.onceDo not confuse with v-once, this click event only fires once
    • v-model.lazyContent is not automatically populated, it is bound when an event occurs

You can also customize the instructions.

We will use these methods in a later example!

Event handling

Data binding is good, but no event handling can be used for a larger purpose, so try it next! This is part of my favorite. We will use the above bindings and listeners to listen for DOM events.

There are several different ways to create an available method in your application. For example, in the ordinary JS, you can choose the function name, but the instance method is intuitively called methods!

New Vue ({  el: ' #app ',  data () {   return {    counter:0   }  },  methods: {   increment ( ) {     this.counter++;}}  );
<div id= "App" >  <p><button @click = "Increment" >+</button> {{counter}}</p></ Div>

We have created a method named increment and you will notice that the function is automatically bound this , pointing to the instance and data in the component. I like this automatic binding, which does not need to be console.log viewed by this pointing. We use abbreviations to @click bind the click event.

Methods is not the only way to create custom functions. You can also use watch . The difference between the two is that methods is suitable for small, synchronous computations and watch is advantageous for multitasking, asynchronous, or expensive operations that respond to data changes. I often use watch in animations.

Let's take a look at how to pass events and dynamically style bindings. If you remember the table above, you can use it : instead v-bind , so we can simply pass in :style and pass the state, or :class bind the style (and other attributes). This binding does have a lot of use.

In the following example, we use hsl() the hue calculated as a circle of degrees of color, so each position is colored value. This method is useful because any numeric value is valid. So when we move the mouse over the screen, the background color will update accordingly. We use the ES6 template literal.

New Vue ({  el: ' #app ',  data () {    return {      counter:0,      x:0    }  },  methods: {    Increment () {      this.counter++;   },   decrement () {     this.counter--;   },   Xcoordinate (e) {     this.x = E.clientx;}}  );
<div id= "app": style= "{backgroundcolor: ' HSL (${x}, 80%, 50%) '}" @mousemove = "Xcoordinate" >  <p>< Button @click = "Increment" >+</button> {{counter}} <button @click = "Decrement" >-</button></p >  <p>pixels Across: {{x}}</p></div>

You should see that we don't even need to pass @click events, and Vue automatically passes it as an argument to the method (shown here e ).

In addition, native methods can be used, for example event.clientX , and are easily associated with this instances. In the style binding of an element, the CSS property needs to be named with the hump. In this example, you can see that Vue is simple and straightforward.

In fact, we don't even need to create a method, and if the event is simple enough, we can also add the counter's value directly in the component:

<div id= "App" >  <div class= "Item" >     <div class=    "Quantity" > <button class=      "Inc" @ click= "Counter > 0? Counter-= 1:0 ">-</button>      <span class=" Quant-text ">quantity: {{counter}}</span>      < Button class= "inc" @click = "counter + = 1" >+</button>    </div>    <button class= "submit" @click = " ">Submit</button>  </div><!--item--></div>
New Vue ({  el: ' #app ',  data () {    return {      counter:0    }}}  );

Instead of using any method, we modify the state directly in the @click event. And we can add a bit of logic to it (because there won't be less than 0 in the shopping site). Once this logic is too complex, even if the readability is reduced, it is best to write to a method. It's a good choice.

Vue.js Series Tutorial 1: Rendering, directives, events

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.