Obtaining back-end data for Vue element front-end application development

Time:2021-11-27
catalogue
  • summary
  • 1. Acquisition and processing of back-end data
  • 2. Interface display processing

summary

In the previous essay “association processing of dynamic menu and route in step-by-step Vue + element front-end application development”, it is introduced that the processing of dynamic menu and dynamic route is realized in the Vue + element integration framework, so that the local route can be filtered and bound according to the menu corresponding to the user role. If the menu is successfully completed, the page function needs to be further developed, This essay introduces a case of processing the product information page after obtaining the back-end data.

1. Acquisition and processing of back-end data

The boundary between the front and back ends is very clear. The front end can build the application of the front end by obtaining the corresponding JSON through the network.

Through the configuration information of vue.config.js, we can specify whether the proxy handles local mock data or actual back-end data, as shown below.

To request data across domains, set the proxy in the configuration file, vue-cli3 project, and write the configuration in vue.config.js.

We have created some API class files for operating data. Each API name corresponds to the centralized processing of a business, including list requests, single requests, addition, deletion, modification, etc. of a specific business, which can be encapsulated in an API class.

Then define our request logic in the corresponding business API access class, such as product.js, which is mainly to use the request auxiliary class that simply encapsulates Axios to realize the data request.

The next step is to define our view file in the Src / views / product directory, that is, the page file, which contains several parts of the regular Vue, including


<template>
  
</template>

<script>
export default {

}
</script>

<style>

</style>

Among them, the < template > is the interface element part, which can add our relevant interface components, such as the interface component of element.

Among them, < script > is the part of Vue script interaction, which encapsulates many of our processing logic and corresponding modal object information. Before calling API classes to access data, we often need to introduce corresponding API class files, as shown below.


import { GetTopBanners, GetProductList } from '@/api/product'

Where < style > defines the relevant style.

At the beginning of the introduction to Vue’s script, we think you have learned about Vue’s script and its life cycle. The script includes:.

<script>
export default {
  data() {
    return {};
  },
  methods: {
    //Component method
  },
  watch: {
    //Scenarios that watch is good at: one data affects multiple data
  },
  computed: {
    //Computed is good at processing scenarios: one data is affected by multiple data
  },
  beforeCreate: function() {
    //After instance initialization, data observer and event / watcher events are called before configuration.
  },
  created: function() {
    //Called after the instance has been created. In this step, the instance has completed the following configuration: Data observer, operation of properties and methods, and callback of watch / event events. However, the mount phase has not yet started and the $El attribute is not currently visible.
  },
  beforeMount: function() {
    //Called before the mount starts: the related render function is called for the first time.
  },
  mounted: function() {
    //The event hook executed after the compiled html is mounted on the page
    // El is replaced by the newly created vm.$el, and the hook is invoked after mounting to an instance.
    //This hook function usually makes some Ajax requests to obtain data for data initialization
    console.log("Home done");
  },
  beforeUpdate: function() {
    //Called when the data is updated, which occurs before the virtual DOM is re rendered and patched. You can further change the state in this hook, which does not trigger an additional re rendering process.
  },
  updated: function() {
    //The hook is invoked after the virtual DOM is re rendered and patched due to data changes.
    //When this hook is called, the component DOM has been updated, so you can now perform DOM dependent operations. However, in most cases, you should avoid changing the state during this period, as this may lead to an infinite loop of updates.
    //The hook is not called during server-side rendering.
  },
  beforeDestroy: function() {
    // before the instance is destroyed, it is called. At this step, the instance is still fully available.
  },
  destroyed: function() {
    // after the Vue instance is destroyed, it is called. After calling, everything indicated by the Vue instance will be unbound, all event listeners will be removed, and all sub instances will be destroyed. The hook is not called during server-side rendering.
  }
};
</script>

Among them, we mainly involve the following contents:

Data, which is used to define the modal object or attribute of the whole page,

Method, which is used to define various processing methods

Computed, used to define the tree of some calculations

Created is used when the element is created but not mounted

Mounted, when the page is mounted

2. Interface display processing

For example, if we want to show the content of an interface, we need to show the pictures of the product and the introduction of the product information

Then you need to define relevant data templates and corresponding processing methods to realize data binding processing before page loading.


export default {
  data() {
    return {
      activeName: 'all',
      currentDate: new Date(),
      banners: [],
      productlist: [],
      pageinfo: {
        pageindex: 1,
        pagesize: 10,
        total: 0
      },
      producttype: 'all'
    };
  },
  created() {
    this.loadbanners()
    this.getlist()
  },

In the interface part, we use the interface component of element to define the display effect of a walking lantern, as shown below.

The interface elements defined in the template module are as follows.

The El carousel is the walking lamp of the element component, and V-for = “itembanners” is the processing syntax of Vue, which circularly processes the data in the data model, and then displays multiple pictures one by one, so as to realize the effect display of the walking lamp.

For list display, we use the display content of a card and pagination to display data.

For the category button, the code is as follows.

<el-row :gutter="20" style="padding:20px">
  < El button type = "primary" icon = "El icon search": plain = "ProductType! ='All '" @ Click = "handleclick ($event,' all ')" > all < / El button >
  < El button type = "success" icon = "El icon search": plain = "ProductType! ='1 '" @ Click = "handleclick ($event,' 1 ')" > framework product < / El button >
  < El button type = "warning" icon = "El icon search": plain = "ProductType! ='2 '" @ Click = "handleclick ($event,' 2 ')" > software product < / El button >
  < El button type = "danger" icon = "El icon search": plain = "ProductType! ='3 '" @ Click = "handleclick ($event,' 3 ')" > develop components < / El button >
</el-row>

It mainly controls some styles according to the data attribute and responds to the corresponding click event.

The demo code of each card is shown below.

<el-col :span="4"><div />
<el-card>
  <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png">
  <div style="padding: 14px;">
    <span>Delicious hamburger</span>
    <div>
      < time > price: ¥ 200 < / time >
      < El button type = "text" @ Click = "loadbanners()" > operation button < / El button >
    </div>
  </div>
</el-card>
</el-col>

However, we need to bind according to the actually obtained dynamic data, so we need a loop to process it. Similar to the V-for loop above, we can display the product list.

<el-col v-for="(item, index) in productlist" :key="index" :span="4" style="min-width:250px">
<div>
  <el-card>
    <img :src="item.Picture" style="width:200px;height:200px">
    <div style="padding: 14px;">
      <span>{{ item.ProductName }}</span>
      <div>
        <!-- < Time > price: ¥ {{item. Price} < / time > -- >
        < El button type = "text" > operation button < / El button >
      </div>
    </div>
  </el-card>
</div>
</el-col>

In order to effectively request and display data, we also need to use the paging component to query the data. The definition code of the paging component interface is as follows.


 <el-pagination
      background
      layout="prev, pager, next"
      :page-sizes="[10,20,50]"
      :total="pageinfo.total"
      :current-page="pageinfo.pageindex"
      :page-size="pageinfo.pagesize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

In order to realize data paging, we need to define several variables, such as the current page number, the data size of each page, and the total number of data records, to meet the needs of paging query.

The method of GetList we define is as follows.

getlist() {
      //Constructing paging query criteria
      var param = {
        type: this.producttype === 'all' ? '' : this.producttype,
        pageindex: this.pageinfo.pageindex,
        pagesize: this.pageinfo.pagesize
      };

      this.listLoading = true
      //Initiate a data query request and set the value of local data
      GetProductList(param).then(data => {
        this.productlist = data.list
        this.pageinfo.total = data.total_count
        this.listLoading = false
      })
    },

In addition, several methods are defined to query the data.

//Click a category to query
    handleClick(e, type) {
      // console.log(e, type);

      this.producttype = type
      this.pageinfo.pageindex = 1;

      this.getlist()
    },
    //Query processing after changing the number of pages
    handleSizeChange(val) {
      Console.log (` ${Val} entries per page);
      this.pageinfo.pagesize = val;
      this.getlist()
    },
    //Query processing after page number change
    handleCurrentChange(val) {
      Console.log (` current page: ${Val} ');
      this.pageinfo.pageindex = val;
      this.getlist()
    }

The above is the basic operation of data paging query request by using element interface components and Vue methods. Through this simple case, we can understand the use of some basic element interface components, understand data / method and other contents, and guide how to encapsulate and call cross domain API requests, Realize the display and processing of back-end data on the interface.

The above is the details of obtaining back-end data for Vue element front-end application development. For more information about obtaining back-end data for Vue element, please pay attention to other relevant articles of developeppaer!