In this article, we will explain the Props and Methods of Vue instances, then we will explain the most common Vue template syntax and put it into practice with examples, and finally we will explain the composition of Vue components and complete our publishing product page.

Welcome to the Series from Zero to Deployment: Implementing Mini Full Stack E-commerce Applications with Vue and Express:

  • From Zero to Deployment: Implementing Mini Full Stack E-commerce Applications with Vue and Express (PART 1)
  • From Zero to Deployment: Implementing Mini Full Stack E-commerce Applications with Vue and Express (PART 2)
  • From Zero to Deployment: Implementing Mini Full Stack E-commerce Applications with Vue and Express (Part 3)
  • From Zero to Deployment: Implementing Mini Full Stack E-commerce Applications with Vue and Express (4)
  • From Zero to Deployment: Implementing Mini Full Stack E-commerce Applications with Vue and Express (5)
  • From Zero to Deployment: Implementing Mini Full Stack E-commerce Applications with Vue and Express (6)
  • From Zero to Deployment: Implementing Mini Full Stack E-commerce Applications with Vue and Express (7)
  • From Zero to Deployment: Implementing Mini Full Stack E-commerce Applications with Vue and Express (Final)

If you think we wrote well, remember to like + follow + comment three times, encourage us to write a better tutorial 💪

Add data using template syntax and two-way binding

Once we have the basic page framework for the Mall app, we can start thinking about the content of the specific page. The first thing we need to consider is the source of the data, which is to add the product page. With an entry for adding items, we can display a list of items, get product details, and even modify product information.

But before we do, we’re going to go over some important Vue points. If you’re already familiar with this, you can skip to the section below that implements ProductForm.vue.

Vue instances: Props and Methods

Props

Props is the form in which Vue passes parameters between components. For example, we have two components: new. vue and productForm. vue. We need to use productForm. vue in the new. vue component. Where the new.vue component is used to create an item, its code looks something like this:

import ProductForm from '@/components/ProductForm.vue';

<ProductForm :manufacturers="manufacturers" />
Copy the code

It needs to pass a Manufacturers attribute to the ProductForm.vue component to ensure that when we create an item, we can select the manufacturer that the item belongs to, Then we can get the Manufacturers property in props in productForm. vue. The code for productForm. vue looks something like this:

<template>
<! -- Template section -->
</template>

<script>
export default {
  props: ['manufacturers'],}</script>
Copy the code

As you can see, in the productForm. vue script exported object, we find the props property and get the Manufacturers property.

Methods

Then there are methods, which are used to define the methods that are used in components. If data flows from the logical layer (JS) to the view layer (Html), then methods are the view layer triggering events. Methods, such as Click and Submit, in turn modify the data of the logical layer. Methods make data flow in both directions.

Let’s refine our productForm. vue and see how Methods work in vue:

<template>
<form @submit.prevent="saveProduct">
<! -- Other forms such as input -->

<div class="form-group new-button">
  <button class="button">Add Product</button>
</div>
</form>
</template>

<script>
export default {
  data: { isSaved: false },
  props: ['manufacturers'].methods: {
    saveProduct() {
       this.isSaved = true;

      // Complete some logic to save creating goods...}}}</script>
Copy the code

As you can see, we can invoke the saveProduct method defined in the Methods property in script by invoking the form submission event by clicking the submit button in the Template (view layer). This method further modifies the data defined in the data attribute; Even if the parent component new.vue passes a method (in the form of props) to the ProductForm.vue component, we can call the passed method in saveProduct and affect the data in the parent component new.vue. We will cover this later when we formally implement the ProductForm component.

Template syntax: V-ON

Let’s talk about V-bind and V-ON.

In Vue, we take over the onEvent in HTML by v-on:

For example, in HTML we wrote it like this:

<div onclick="alert('I love tuture')">
Hello Tuture
</div>
Copy the code

Now in Vue’s template syntax we need to write:

<div v-on:click="alert('I love tuture')">
Hello Tuture
</div>
Copy the code

Similar onEvent should be changed to V-on :Event. And then it’s a little redundant, so Vue supports simplified writing, replacing the V-on: part with @, and we can write it like this:

<div @click="alert('I love tuture')">
Hello Tuture
</div>
Copy the code

After calling the event, we usually have some actions like disabling the browser default behavior and then processing the event ourselves to get the backend data. We used to write:

<div onclick="saveProduct()">
Hello Tuture

<script>
var saveProduct = function (e) {
  e.preventDefault();

  // do something you like
}
</script>
Copy the code

However, this is too tedious to write, and Vue thinks it will simplify, so we directly treat these calls to disable default behavior as properties of the binding event, so in Vue we can write like this:

<template>
  <div @click.prevent="saveProduct">
  Hello Tuture
  </div>
</template>

<script>
export default {
  methods: {
    saveProduct() {
      // do something you like}}}</script>
Copy the code

Do not know read the above long article, you have a little dizzy, whether you dizzy or not, I have to drink a drink of water for a while. – v –

Template syntax: V-bind

We have seen that we can use the following functionality in the Vue template:

  • {{}}Interpolation syntax willdataRender to HTML element content
  • v-onOr we could simplify it@, etc instead of HTML event binding

Vue template syntax provides a Vue template syntax that allows you to dynamically bind attributes, such as id, class, etc. The Vue template syntax allows you to dynamically bind attributes. Let’s look at an example:

<template>
<option v-bind:id="_id"  v-bind:value="value" />
</template>

<script>
export default {
  data: { _id: '1'.value: "Xiaomi"}},</script>
Copy the code

As you can see, we define _id and value in the data attribute exported from script. Then we dynamically assign the id and value attributes of the option tag by using the V-bind syntax in the

<option id="1" value="Xiaomi" />
Copy the code

Of course, writing v-bind every time is tedious when there are more attributes to bind, so Vue provides us with a concise v-bind syntax: our previous binding syntax changed from v-bind:id=”_id” to :id=”_id”.

The above code is rewritten in concise syntax as follows:

<template>
<option :id="_id"  :value="value" />
</template>

<script>
export default {
  data: { _id: '1'.value: "Xiaomi"}},</script>
Copy the code

Template syntax: V-model bidirectional binding

As mentioned above, {{}} interpolation syntax is used to render the data from data to realize the data flow from the logical layer to the view layer, and methods are used to operate the data of the logical layer at the view layer to realize the data flow from the view layer to the logical layer, thus achieving the two-way binding. As our application becomes more and more complex, We will find that the two-way flow of data will become more frequent, and the granularity will be different. Many method calls that simply modify a value will be particularly complicated. Therefore, Vue provides a two-way binding between the view layer and the logic layer by providing v-model.

<template>
<! Other code... -->
<input
  type="text"
  placeholder="Name"
  v-model="name"
/>
<! Other code... -->
</template>

<script>
export default {
  data: { name: 'ProductForm'}},</script>
Copy the code

Here we declare v-mode to bind the value of the input to the name property of the model in the Vue instance. That is, when the name in data changes, the value of the input will also change. When the value of the input changes, The value of name in our data is also changed automatically, without the need to add an additional method call from Methods to change it manually.

Template syntax: loops

Well, Vue takes over HTML element attribute values, event handling, and element content for us, all of which are still part of the original HTML. What’s more powerful about Vue is that it introduces JS capabilities into template syntax, allowing us to implement functions like loops, conditional selection, and so on.

Let’s take a look at Vue’s “loop” template syntax, which allows us to quickly render large amounts of data with similar structures, such as rendering an array of data to generate a list of HTML elements. This is common in news apps. When we browse news, We found that the structure of each news item was similar, and there were many news items (maybe hundreds or thousands of news items). If we wrote the HTML code manually for each news item, it would be quite tedious. Moreover, we could not do anything manually with a large number of data. This allows us to render large amounts of data with very simple writing. Let’s look at an example:

<! -- manufacturers = [ { _id: 1, name: 'Apple' }, { _id: 2, name: 'Xiaomi' } ] model = { _id: 1, name: 'Apple' } -->
<template v-for="manufacturer in manufacturers">
  <option :value="manufacturer._id" :selected="manufacturer._id == model._id">{{manufacturer.name}}</option>
</template>
Copy the code

The final render result is:

<option value="1" selected="true">Apple</option>
<option value="2" selected="false">Xiaomi</option>
Copy the code

Note that if we write the “loop” syntax using an extra tag template to wrap the HTML elements we need to render, this is what Vue recommends; We iterate over the list by adding v-for to the template attribute and assigning it the “manufacturer in Manufacturers “value, one element at a time, Assign to the manufacturer, and then we can compare the manufacturer with the model we defined in the Option tag.

Because our model._id is 1, which matches the _id of the first element in the Manufacturers array, we return two option tags. The first selected attribute is true, and the second is false.

Template syntax: conditional selection

The above shows how loops are used in Vue. Let’s take a look at how conditional syntax is used in Vue:

<span v-if="isEditing">Update Product</span>
<span v-else>Add Product</span>

<script>
export default {
  data: { isEditing: false}},</script>
Copy the code

We can see that we can determine the final render tag by adding v-if to the tag followed by v-else. For example, if the isEditing is false, then the final render tag is:

<span>Add Product</span>
Copy the code

Of course you can add tags like V-else -if to make multiple judgments.

prompt

Tags with v-if, V-else, or V-else attributes need to be followed by the preceding tags. You cannot insert other tags without conditions in these tags. For example:

<span v-if="isEditing">Update Product</span>
<span>I inserted the label by mistake</span>
<span v-else>Add Product</span>

<script>
export default {
  data: { isEditing: false}},</script>
Copy the code

implement

After explaining the basics of Vue, we immediately put all that knowledge to use to write our ProductForm. Vue component, which adds or updates the product information.

We create the productForm. vue form component in SRC/Components as follows:

<template>
  <form @submit.prevent="saveProduct">
    <div class="col-lg-5 col-md-5 col-sm-12 col-xs-12">
      <div class="form-group">
        <label>Name</label>
        <input
          type="text"
          placeholder="Name"
          v-model="model.name"
          name="name"
          class="form-control" />
      </div>
      <div class="form-group">
        <label>Price</label>
        <input
          type="number"
          class="form-control"
          placeholder="Price"
          v-model="model.price"
          name="price" />
      </div>
      <div class="form-group">
        <label>Manufacturer</label>
        <select
          type="text"
          class="form-control"
          v-model="model.manufacturer"
          name="manufacturer">
          <template v-for="manufacturer in manufacturers">
            <option :value="manufacturer._id" :selected="manufacturer._id == (model.manufacturer && model.manufacturer._id)">{{manufacturer.name}}</option>
          </template>
        </select>
      </div>
    </div>

    <div class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
      <div class="form-group">
        <label>Image</label>
        <input
          type="text"
          lass="form-control"
          placeholder="Image"
          v-model="model.image"
          name="image"
          class="form-control" />
      </div>
      <div class="form-group">
        <label>Description</label>
        <textarea
          class="form-control"
          placeholder="Description"
          rows="5"
          v-model="model.description"
          name="description"
         ></textarea>
      </div>
      <div class="form-group new-button">
        <button class="button">
          <i class="fa fa-pencil"></i>
          <! -- Conditional rendering for input text -->
          <span v-if="isEditing">Update Product</span>
          <span v-else>Add Product</span>
        </button>
      </div>
    </div>
  </form>
</template>

<script>
export default {
  props: ['model'.'manufacturers'.'isEditing'].methods: {
    saveProduct() {
      this.$emit('save-product'.this.model)
    }
  }
}
</script>
Copy the code

This code looks pretty long, and it may scare you, but let’s break it down one paragraph at a time.

Script part

Here our props receives three arguments from the parent component: Model, Manufacturers, isEditing.

Then we define a saveProduct method, which will be triggered when the user clicks the submit button after filling in the form of product information. Inside saveProduct, we call the save-product method of the parent component. And passes the modified contents of the this.model variable to the parent component. Therefore, we can also see that methods can not only make data flow in both directions, but also reverse the content of the parent component in the child component, making data flow up and down.

Template section

Now let’s talk about what happens inside the template.

The template contains a form that defines a Submit event and uses the shorthand @submit.prevent to disable the default event. This event trigger calls the saveProduct method we mentioned above.

We then define several blocks of elements whose class is a form-group. Each block represents the information we need to fill in to create the item. We notice that The first two form-groups bind the Name and price attributes of the Model, respectively, using the V-Model two-way binding syntax.

For the third form-group, we first bind the Model. Manufacturer attribute to the V-Model bidirectionally in the select tag, indicating that we will modify the corresponding Model.

We then loop through manufacturers, construct multiple option tag options, and bind the value and selected properties of option using the shorthand of property binding syntax. The value attribute is set to manufacturer._id, and the selected attribute checks that, Model.manufacturer && model.manufacturer._id indicates that the manufacturer attribute of the model exists first. It should normally be an object. If the model.manufacturer attribute exists, get the model.manufacturer._id and compare the obtained model.manufacturer. The selected property is true, false if inconsistent.

Let’s look at the second paragraph of the form group, which is 4-6 form groups.

It can be seen that the first two form-groups bind model.image and model.description bidirectionally using V-model, indicating that after the user uploads the product picture and description, the corresponding model.image becomes the product picture uploaded by the user. Model.description becomes a user-written description of the product.

In the last form-group, we used conditional selection syntax to determine isEditing to render different button text.

Vue component composition

After writing the form above, we introduce the form component we created in new.vue:

<template>
  <product-form
    @save-product="addProduct"
    :model="model"
    :manufacturers="manufacturers"
  >
  </product-form>
</template>

<script>
import ProductForm from '@/components/products/ProductForm.vue';
export default {
  data() {
    return {
      model: {},
      manufacturers: [{_id: 'sam'.name: 'Samsung'}, {_id: 'apple'.name: 'Apple',}]}; },methods: {
    addProduct(model) {
      console.log('model', model); }},components: {
    'product-form': ProductForm
  }
}
</script>
Copy the code

When a component wants to use another component in template syntax, it is required to declare the component to be used in the component’s components property. For example, we used the name ‘product-form’ to declare the ProductForm component. This allows us to use the imported form component in the template as .

We also define model and Manufacturers in the component’s data and addProduct in methods, And pass them to the form component as property bindings :model=”model”, :manufacturers=”manufacturers”, and event bindings @save-product=”saveProduct”.

After saving the code we wrote above, we open the browser, click the navigation link Admin, and then click the sub-navigation link New Products to switch to our New. Vue add Products page, we can see the following effect:

summary

So far, we’ve looked at the basics of Vue, including:

  • Use routing to jump and navigate multiple pages
  • Organize pages properly with nested routing and dynamic routing
  • Vue components and Vue instances
  • Vue template syntax

After mastering this knowledge, we can already realize many front-end functions and complete some simple Vue applications. However, if you want to complete complex large-scale applications of data logic, the current knowledge is not enough. But that’s ok. We’ll learn about Vuex as a front-end state management tool later. With the help of Vuex, we can write any complex application with Vuex.

Want to learn more exciting practical skills tutorial? Come and visit the Tooquine community.