"Vue Basics" Quick Start for Newbies (1)

"Vue Basics" Quick Start for Newbies (1)

Since Facebook launched the React framework in 2013, front-end frameworks based on UI components have become more and more popular, mainly due to the reusability of components and the management of data states.

Google also launched the second-generation component-based Angular framework, dedicated to the development of full-platform applications-Web, mobile Web, mobile applications, native applications and desktop native applications. Its core features are: MVC, modularity, and two-way automation. Data binding, semantic labeling, dependency injection, etc.

The late show Vue.js, whose author You Yuxi was created when he took office at Google and released it in 2014. Since its release, it has been designed to be flexible, easy to integrate into existing projects, and to easily build complex applications. Vuejs is very popular and has now become one of the three mainstream front-end frameworks.

Why choose Vue?

When you read this article, you must be wondering why you chose Vue. Can the following reasons move you to choose Vue?

1. It is easy to integrate and get started with existing projects. You can easily integrate Vue into your existing website without introducing new tools to set up complex processes. If you are used to using jQuery, you can easily get started with Vue. 2. Architecture based on **component**. Allows applications to be modularized and componentized, which facilitates the rapid construction of modern single-page applications (SPA). 3. ** The integrity of the ecology. You can find almost every plugin you can think of in the community. More importantly, its important libraries such as routing and state management are maintained by the official Vue team. Unlike the React ecosystem, the official is not very active in providing solutions. 4. **Widely used**. From foreign GitLab to domestic Alibaba, especially the use of more and more domestic companies, it has become a must-have skill for the domestic front-end. At the same time, Vue.js has become the default front-end library of Laravel, a popular PHP framework. Due to its widespread use, more people will invest in this framework in the future to make its ecology more powerful, and each of our developers will benefit the most.

Start the journey

First of all, through the learning of the basic knowledge of Vue.js in this article, the author will take everyone to complete the exercises shown in the following figure:

Mainly realize the following functions:

  1. Complete the layout of the page effect
  2. Introduce the Vue framework to achieve data rendering
  3. Click on the header to sort the information according to the attributes of the header

Introduce Vue

In order to make it easy for everyone to get started quickly with Vue, this article uses the simplest way to introduce JS files to introduce the Vue framework. In the next article, the author will introduce in detail the way to create a vue project by building. Create a new index.html file to introduce the Vue file as shown below :

Note: The development version is introduced to facilitate our development and debugging. The production environment should introduce the vue.min.js version

Next we create a Vue instance, the code is as follows:

new Vue({
  el: "#main"
});

The meaning of this piece of code is to declare a Vue instance and find the element whose DOM id is equal to main for the next presentation of data content.

Download Data

In order for the above Vue instance to load data, we need to provide data. The data attribute is provided in Vue for loading data sources. The data attribute is responsive. When the value of these attributes changes, the view will produce a "response", that is, the match is updated to the new value and affects the display of the UI.

Next, we add some data to the data attribute. In the actual application scenario, you will request data through the interface. For the convenience of demonstration, we will write some data. Examples are as follows:

new Vue({
  el: "#main",
  data: {
    heading: "Front-end expert development department",
    employees: [
      {
        "firstName": "amelia",
        "lastName": "austin",
        "photoUrl": "https://www.qianduandaren.com/demo/vue/img/women/1.jpg",
        "email": "amelia.austin@example.com",
        "phone": "(651)-507-3705",
        "department": "Engineering"
      },
      {
        "firstName": "bobbie",
        "lastName": "murphy",
        "photoUrl": "https://www.qianduandaren.com/demo/vue/img/women/2.jpg",
        "email": "bobbie.murphy@example.com",
        "phone": "(925)-667-7604",
        "department": "Management"
      }
    ]
  }
});

Template syntax{{}}

Now that we have the data, we need to render and present the interface data. We need to use template syntax-a pair of braces ({{}}) for data binding. As shown in the following code:

<h1 class="ui center aligned header">{{ heading }}</h1>

You can include any valid JavaScript code in these double curly braces, as shown below, we include an arithmetic statement in it:

<div id="app">
  <p>The price is: ¥{{ price * 1.20 }} (inc. VAT)</p>
</div>
<script>
  new Vue({
    el:'#app',
    data: {
      price: 25
    }
  });
</script>

The double bracket area will be displayed

The price is: ¥30 (inc. VAT)

In the example, before the interface is presented, the calculation of the JS statement is performed and the value is displayed.

instruction

To achieve a more complex page program, you can't just present simple data. Therefore, Vue's template syntax also contains logic instructions for looping and conditional display, allowing us to better handle the page display logic. The responsibility of the instruction is to act on the DOM responsively when the value of the expression changes. (Similar to the ng-* directive of AngularJS)

v-for

Earlier we introduced an example of loading data. You may have guessed that we need to use a loop traversal method to traverse the collection for data display. The function of the v-for instruction is to traverse each item in the data collection, as shown in the following code:

<tbody>
  <tr v-for="employee in employees">
    <td>
      <img src="https://www.qianduandaren.com/demo/vue/img/women/1.jpg"
              class="ui mini rounded image"/>
    </td>
    <td>{{ employee.firstName }}</td>
    <td>{{ employee.lastName }}</td>
    <td>{{ employee.email }}</td>
    <td>{{ employee.phone }}</td>
    <td>{{ employee.department }}</td>
  </tr>
</tbody>

From the above code, we can see that we have added the v-for instruction to the tr attribute, which represents a loop in this DOM area, and we display the employee's information in this loop. Here we have written the src attribute of the picture to death, and we will soon introduce the new command to replace it.

As with react, when rendering lists in Vue, it is strongly recommended that you provide a unique key for each element. This helps the Vue framework to optimize when adding and removing elements. You can use the :key command to define unique key values:

<tr v-for="user in users" :key="user.id>

If there is really no unique key value, you can use an array index, the sample code is as follows

<tr v-for="(employee, index) in employees" :key="index">..</tr>

v-if

Another common instruction is conditional rendering, v-if only when the data attribute or the calculation result of the expression is true, the use of this instruction will cause Vue to render the element, as shown in the following code:

<tbody>
  <tr v-for="employee in employees">
    ...
  </tr>
  <tr v-if="employees.length === 0">
    <td colspan="6">No employees found</td>
  </tr>
</tbody>

If employee is empty in the above code, the message No employees found will be displayed, which is very useful for the logical processing of calling API to load data in the future.

If there is a v-if instruction, there will naturally be a v-else-if instruction to handle more complex condition processing, as shown in the following code:

<tbody>
  <tr v-for="employee in employees"> ... </tr>
  <tr v-if="isLoadingData">
    <td colspan="6"><img src="spinner.gif"/></td>
  </tr>
  <tr v-else-if="employees.length === 0">
    <td colspan="6">No employees found</td>
  </tr>
</tbody>

From the above code, we have added an isLoadingData attribute, which is very useful in our logical processing of dynamically loading data, because asynchronous loading of data involves network delays and other issues. Before data is loaded, there needs to be a message to remind the user that the data is being loaded.

v-bind

Sometimes, you need to bind data to the attributes of the html element, such as the href attribute on the url and the src attribute of the img.

Remember our example above, when we rendered the data, we wrote the img attribute to death. Now we can use the v-bind command to bind the data, the code is as follows:

<img v-bind:src="employee.photoUrl" class="ui mini rounded image"/>

In addition to the above writing, we can use a shorter syntax, just use the: prefix in front of the attribute, the code is as follows:

<img :src="employee.photoUrl" class="ui mini rounded image"/>

v-model

Vue also supports the concept of two-way binding of forms, allowing us to dynamically change the content of data through form input, as shown in the following code:

<div id="app">
  <input v-model="text" placeholder="edit me">
  <p>Text is: {{ text }}</p>
</div>

<script>
new Vue({
  el:'#app',
  data: {
    text:'Good golly, Miss Molly'
  }
});
</script>

From the above example, the v-model instruction binds the data to the form input box. When we change the value of the input box, the content of the p tag area also changes.

v-on

We can use v-on: to bind event listeners, and the event type is specified by the parameter. The expression can be the name of a method or an inline statement, or it can be omitted if there is no modifier.

As shown in the following code, the logic is simple. Click the button to change the attribute of the data heading to Hello World. We have realized the binding of the inline statement:

<button v-on:click="heading ='Hello World!'">Click Me</button>

In addition to using the v-on:click syntax, we can use a shorter syntax for binding-@click. In the above example, we have implemented property changes, and we can also bind custom user methods, as shown in the following code Show:

new Vue({
  el: "#main",
  data: {
    status: ""
  },
  methods: {
    updateStatus(event) {
      const buttons = ['left','middle','right'];
      this.status = `You clicked the ${buttons[event.button]} button.`;
    }
  }
});
<div id="main">
  <button @mousedown="updateStatus" @contextmenu.prevent="">Toggle Me!</button>
  <p>{{ status }}</p>
</div>

In the above code, we bind the mousedown event to the updateStatus method to help the user determine whether the left mouse button or the right button is clicked. At the same time, we added a second event listener contextmenu.prevent to prevent the default context menu behavior of the right mouse button. . Similarly, there are other common event modifiers:

.stop: Stop the event from bubbling. .prevent: Prevent browser default behaviors, such as page scrolling. .capture: Flip the event propagation direction. Originally, the event is executed from the innermost element to the outer element, which is called event bubbling. Capture is just the opposite, allowing elements to propagate events from the outside to the inside. .self: The element is only executed on the bound element. .once: The bound event is executed only once, and then it becomes invalid.

Methods

There are special Methods attribute in the Vue object, which is convenient for us to customize related methods and call them easily in the template. As in the previous example, we define methods like this:

methods: {
  updateStatus(event) {
    const buttons = ['left','middle','right'];
    this.status = `You clicked the ${buttons[event.button]} button.`;
  }
}

Computed

Sometimes you need to customize related methods to monitor the data in the calculation template and respond accordingly. If you want to avoid unnecessary method overhead, you can use Vue's "calculated properties" solution.

A calculated attribute is actually a function used to cache and return data. Its function depends on a data item. When the data item changes, its function must be recalculated to perform new data output.

In order to practice this property, we add a sort field property to the data item, as shown below:

data: {
  heading: "Staff Directory",
  sortBy: "firstName"
  employees: [
    ...
  ]
}

Next, we add a click processing event in the title bar to change the property of sortBy, as shown in the following code:

<tr>
  <th>Avatar</th>
  <th @click="sortBy ='firstName'">First Name</th>
  <th @click="sortBy ='lastName'">Last Name</th>
  <th @click="sortBy ='email'">Email</th>
  <th @click="sortBy ='phone'">Phone</th>
  <th @click="sortBy ='department'">Department</th>
</tr>

Finally, let us add a calculated attribute to the Vue attribute, which sorts the data according to the key value, as shown in the following code:

computed: {
  sortedEmployees() {
    return this.employees.sort((a, b) => a[this.sortBy].localeCompare(b[this.sortBy]))
  }
}

Next, we change the code of the v-for area and add our calculated attributes. The sample code is as follows:

<tr v-for="(employee, index) in sortedEmployees" :key="index">
  ...
</tr>

Due to the magic sugar provided by the Vue statement, the output data sortedEmployees is cached. When the sortBy property changes, the value of sortedEmployees will be recalculated.

Finished code

Based on the previous knowledge content, our final index.html code is as follows:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue Staff Directory-Jump Start Vue.js</title>

    <link rel="stylesheet" href="https://www.qianduandaren.com/demo/vue/semantic.min.css">
    <style>
        h1.ui.center.header {
            margin-top: 3em;
        }
    </style>
</head>

<body>
    <main id="main">
        <h1 class="ui center aligned header">{{ heading }}</h1>
        <div class="ui container">
            <table class="ui celled table">
                <thead>
                    <tr>
                        <th>Avatar</th>
                        <th @click="sortBy ='firstName'">First Name</th>
                        <th @click="sortBy ='lastName'">Last Name</th>
                        <th @click="sortBy ='email'">Email</th>
                        <th @click="sortBy ='phone'">Phone</th>
                        <th @click="sortBy ='department'">Department</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(employee, index) in sortedEmployees" :key="index">
                        <td>
                            <img :src="employee.photoUrl" class="ui mini rounded image"/>
                        </td>
                        <td>{{ employee.firstName }}</td>
                        <td>{{ employee.lastName }}</td>
                        <td>{{ employee.email }}</td>
                        <td>{{ employee.phone }}</td>
                        <td>{{ employee.department }}</td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="6"></th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        new Vue({
      el: "#main",
      data: {
        heading: "Front-end expert development department",
        sortBy:'department',
        employees: [
                    {
                        "firstName": "amelia",
                        "lastName": "austin",
                        "photoUrl": "https://www.qianduandaren.com/demo/vue/img/women/1.jpg",
                        "email": "amelia.austin@example.com",
                        "phone": "(651)-507-3705",
                        "department": "Engineering"
                    },
                    {
                        "firstName": "bobbie",
                        "lastName": "murphy",
                        "photoUrl": "https://www.qianduandaren.com/demo/vue/img/women/2.jpg",
                        "email": "bobbie.murphy@example.com",
                        "phone": "(925)-667-7604",
                        "department": "Management"
                    },
                    {
                        "firstName": "kristin",
                        "lastName": "terry",
                        "photoUrl": "https://www.qianduandaren.com/demo/vue/img/women/3.jpg",
                        "email": "kristin.terry@example.com",
                        "phone": "(021)-544-1184",
                        "department": "Sales"
                    },
                    {
                        "firstName": "brandon",
                        "lastName": "griffin",
                        "photoUrl": "https://www.qianduandaren.com/demo/vue/img/men/1.jpg",
                        "email": "brandon.griffin@example.com",
                        "phone": "(509)-317-9506",
                        "department": "Management"
                    },
                    {
                        "firstName": "tammy",
                        "lastName": "gibson",
                        "photoUrl": "https://www.qianduandaren.com/demo/vue/img/women/4.jpg",
                        "email": "tammy.gibson@example.com",
                        "phone": "(815)-727-0663",
                        "department": "Support"
                    },
        ]
        },
            computed: {
                sortedEmployees() {
                    return this.employees.sort((a, b) => a[this.sortBy].localeCompare(b[this.sortBy]));
                }
            }
        });
    </script>
</body>

</html>

Subsection

That’s it for the content of this article. Next, I will leave you a homework question (the answer will be published in the next article). Based on the example of this article, we add an input box to realize the employee information retrieval function (enter the employee’s full name) Or part of the name, display the information result). In the next article, I will continue to introduce how to build Vue projects and Vue-related tools through engineering, so stay tuned.

Reference: https://cloud.tencent.com/developer/article/1465735 "Vue Basics" Quick Start for Newbies (1)-Cloud + Community-Tencent Cloud