Vue.js Development Record __js

Source: Internet
Author: User
Tags emit
vue.js Development RecordBackground: The development of Yiwu bin Wang 158 Trade City Information Management system, the front-end use of "Hungry Mody" element UI, based on Vue. The main purpose is to beginning something new and replace the existing "JQ kit" for the current breach of the current, and the following are the pit points that have been trampled during the development process and the content to be summarized Scaffold Erection

Found in the GitHub based on the Vue.js 2.x series + Element UI of the background management System solution, the project includes common management system components, webpack and other automated work to be used, the specific project address is as follows:

Https://github.com/lin-xin/vue-manage-system Login Status

The front end is based on Vue single page application, the front and back end completely separates, and the management system for the internal personnel use, to the browser version request is not high, therefore in order to be simple and efficient, the front and back end division of labor more clear, uses the back end focus to provide the data, the login Think of two schemes,cookie&& Localstorage, the former is good for browser compatibility, but the data will be written into the HTTP header, each send request will be carried, the back end does not need the data, the latter requires a higher browser, but completely by the front-end maintenance, Make a clear distinction between the front and back functions. The final option is to use Localstorage to maintain login status.

Another point is that the login status is time-sensitive, the direct use of HTML5 Localstorage did not provide time to set the function, so on the GitHub found a useful extension library (Webstoragecache) Https://github.com/WQTeam /web-storage-cache, which adds a time-out, serializes the method, can store the JSON object directly, and can simply set the timeout time.

Webstoragecache uses the following code:

Import Wscache from ' Web-storage-cache ';
Vue.prototype. $wsCache = new Wscache ();                             
this. $wsCache. Set ("username", username, {exp:60 * 60});

Finally, check the login status is expired, initially through the page routing changes to trigger, when the page address has changed, first of all to determine whether you can get the login from the Localstorage, if you can not jump directly to the landing page to login, if you may continue to jump. This scheme introduces a hook function of Vue-router

Import Router from ' Vue-router ';
var router = new Router ({...});
Router.beforeeach (to, from, next) => {    //Beforeeach is a router hook function that calls
    if (judgestatus) if the route changes   //Judgestatus tool function
        next () to determine whether the login status is expired

Summary, because the initial development time of the project is tight, and is the front and back end complete separation, the login state design is more from the development of convenient and efficient perspective, combined with the project use scene (for internal initial use), the problem is not big. But it still lists the points that need to be improved for subsequent refinement: 1. The security of Localstorage, because the front end is visible, can forge, the security does not have the very good safeguard, the follow-up may consider introduces the token authentication the plan 2. Login status Trigger, the latter can be combined with the interface request level interception, before the request to send the global blocking method. Configuration of Axios

After vue2.0, the official Recommended network interaction option uses Axios, which is based on the Promise HTTP request client.

List its functional characteristics:

Sending xmlhttprequests requests in the browser

Support for Promise APIs

Intercepting requests and responses

Transforming Request and response data

Automatically convert JSON data

Client support protects security against XSRF attacks

In development, "enjoy" to the convenience of functional 2,3,4,5 support Promise API

Code examples are as follows: for the serial sending of Ajax and so on, the code reading is more friendly

Axios.get ('/user?id=12345 ')
  . Then (function (response) {
    Console.log (response);
  })
  . catch (function (response) {
    Console.log (response);
  });
intercepting requests and responses

Intercepts the request, and the system intercepts and sends the data for post requests (because by default, Axios serializes JavaScript objects into JSON.) To send data in an application/x-www-form-urlencoded format, the POST request needs to encode the data.

To intercept the response, the return format of the system backend interface should be returned in strict accordance with the standard after the front and back end negotiation.

Successful return of
{"
  code": "
  Data": {}   //returned to the

failed return of
{
  "code": +,
  "error": {
    ' msg ': ' \ ' failed message \ ' '
  }
}

Axios to the response interception, if successful, continue processing, failure output error message, the end of the request, the response to intercept the failure and success of the global process, saving a lot of duplicate code

The following is the system's interception request and response configuration code

Axios.interceptors.request.use (config) => {
    config.data = qs.stringify (config.data);
    return config;
});
Axios.interceptors.response.use (res) => {
    if (Res.data.code = = ') {
        message.error (res.data.error.msg );
        return null;
    }
    Return Res.data
}, (Error) => {
    message.error ("network exception");
    return Promise.reject (Error);
});
Axios Global Configuration
Axios.defaults.timeout = 5000;  Timeout setting
axios.defaults.headers.post[' content-type ' = ' application/x-www-form-urlencoded ';  
Axios.defaults.baseURL = BaseURL; Global Request URL Front
Communication for parent-child components

Component (Component) is one of the most powerful features of Vue, where components can extend HTML elements, encapsulate reusable code, and at a higher level, components are custom elements, while writing reusable components, communication to parent-child components is critical

The system of multiple picture upload components For example, the parent-child component of the communication instructions. Parent component to introduce child components

Import subassembly import multiimg from '. /common/multiimg.vue ';

Sub-component Name registration components: {' multiimg ': multiimg}

Adding a child component label to template the parent component passes the value

The parent component is required to pass the uploaded image address and the image upload interface address, as follows:

1 Add prop to the Child Component tab

<multiimg:imgarray= "Resources.designer_works": Actionurl= "Imguploadurl" ></MultiImg>

Imgarray and ActionURL are prop names, preceded by: data corresponding to the change

2. subassembly description Prop:props: [' ActionURL ', ' imgarray '] here corresponds to the props value, the child component can carry on the Prophase format type verification

3. Finally, the subassembly can use the passed value directly according to the name in props

Note: If the parent component is referenced and No. sync is used, then the modification of the subassembly is synchronized to the parent component, which implements the two-way binding effect Child component Transfer value

When the parent component's initial value is received, the parent component needs to instantly listen for data changes as the child component's state changes, so the child component is required to pass the value to the parent component in real time

1. Listen for changes in the values that need to be passed use the Vue watch function

2. Trigger Event

Watch: {
    imgs:function (val) {     //IMGs is a variable picture address array this
        . $emit ("Imgschange", Val);  $emit Trigger Event Imgschange is the trigger event name, Val is the value
    }
}

3. The parent component needs to bind the Listener event function and add v-on to the Child Component tab, as follows

<multiimg:imgarray= "Resources.designer_works": Actionurl= "Imguploadurl" v-on:imgschange= "WorksChange" v-on: Handlechange= "HandleImgChange2" ></MultiImg>

When the imgschange is triggered, the parent component invokes the Workschange method and can pass parameters, so the values passed by the subassembly can be processed in the parent component's Workschange method to handle the third party function SDK

This management system needs to quote the characteristics of the laboratory "indoor Map SDK", but the SDK for many years precipitated, all by "JQ kit" development, completely without modularity, component, Vue single page introduction is difficult, because the Map SDK in many other systems used, specifically for Vue to rewrite, not realistic, So using the way of IFRAME, through the way of SRC, completely isolated from the Vue.

However, there are still many problems, such as the following: loading sequence

The indoor Map SDK in the initialization, will need the system data, and the data is sent through the Vue send request to get, so there is vue load first, the case after the IFRAME, so use to Vue life cycle hook function, hook function listed as follows:

Using created to make data request, mounted is the src assignment of IFrame, and the loading of IFRAME and Vue communication

In the initialization, the need for Vue request data transmission to the IFRAME, runtime, the Map SDK in the IFRAME will also have data changes passed to Vue for data preservation, so the communication between them is essential

The interactive scheme of this system is to use the form of the input hidden field

1.vue passing value to IFRAME

First, the created request initial data through the Vue life cycle hook function, the data is bound to the hidden field in the Vue tag, and then the Vue lifecycle hook function mounted the SRC assignment to the IFRAME, loading the Map SDK, the "JQ suite" in the Map SDK. Main.js to add code when the onload

var InfoText = $ (window.parent.document). Find ("Input hidden Domain name"). Val ();

Get the initial data and do the appropriate processing

2.iframe Transfer value to Vue

First need to add the corresponding input hidden fields in the Vue, through the corresponding data field binding, to undertake the change of dynamic values, the local Diagram SDK data changes, add the following code

$ (window.parent.document). Find ("Input hidden Domain name"). val (changed data value). focus (). blur ();

Note: Here is a pit point, that is, Vue does not support manual dynamic binding, that is, if the value of input is modified through the JS code, the binding of the data value will not change, unless it is manual modification, that is, the user by modifying the value in input, The data value of the binding will change accordingly; So here is a small trick, that is, dynamically write values to the input domain, focus on the hidden field, after the Defocus, and then in the Vue of the input hidden field to add @focus listener focus function, by the function to obtain value value to change the data field, To implement a dynamic binding

Finally, attached to the laboratory features "map sdk-teach the third floor demo" (comparable to Baidu indoor map, embarrassing,,,,,,,,)

Practice Vue Front End

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.