Requirejs, Vue, Vuex, Vue-route, do you think that it is feasible?

Source: Internet
Author: User

Before section 51 and a netizen discuss front-end technology, the other side mentions Vue, Vue-route if with Requirejs application. At that time I did not think very clearly, nor can the netizen an accurate reply, but I promise to him after 51 study to give him a reply. It was a one-day study that I got into the study for a week, this procrastination ...

Gossip Few, go to the chase

First, the sample code description

Code Structure Description:

    1. Modules (stored as components, mainly templates and JS objects are divided into two files to write)
      1. Route: Testing the components of a sub-route
      2. Title: A simple component that displays text
    2. App.js: Core class, providing the creation of Vue, methods for loading previous modules components, etc.
    3. Chart.js: A business module for simulation
    4. Index.html: Paging File
    5. LAYOUT.CSS: Overall style file (test require add style file)
    6. Main.js:requirejs configuration file (also a portal file)
      The Ugly:

This example does not have a style, just to verify how require loads a Vue component to Zi Lu by the ability of the dynamic injection, the sample code is downloaded .

Ii. start with the. vue file

A. Vue file can contain three blocks, such as templates, JS class, style (can not), etc. But we can tell through Vue's official website that Vue provides a compile object method that compiles the template into Vnode. And we can see that the template is confused with the JS class by webpack the files that are generated after packing. This also means that the Vue component is a JS object. As shown in the following:

Iii. introduction of Requirejs to Vue, Vuex and Vue-route

The introduction of these three is easy, and the three injected into the Vue object is also relatively simple, it is necessary to solve the dynamic injection to the Vue-route instance injection route, as well as Vuex dynamic join a data module capability. Fortunately, the two-point official website has given the solution:

    • Vue-route how to dynamically inject routes
      According to the official website Help documentation, there is a addroutes method for dynamically injecting routes to routed entities
    • VUEX Module Dynamic Injection
      Also according to official website help document hint has Registermodule method realization.
    • Part of the code implemented:
      Initialize the Vue object
function () {    this. Store = object.create ({        modules:{}    });               This . Vue.use (vuerouter);      This . Vue.use (Vuex);      This New Vuerouter ();       This New this. Vuex.store (this. Store);}

First, an Init method is provided to initialize the Vue object, which is to inject Vuex and Vue-route into the Vue object. Here I put the created Vuex and Vue-route instances into the This object, which is convenient to provide for the component registration for real use later.
To create a Vue instance:

Apt.createvue =function(){     This. Vue =New  This. Vue ({store: This. Store, Router: This. Router, computed: {childs:function(){                if(! This. $store. State.router)return NULL; return  This. $store. State.router.childs;    }        }    }); return  This. Vue;

Only the Vue object is created, not mount.
The context provided for the other modules:

function () {    return  {        this. Vue,        this. Router,        this. Vue    };}
Iv. How to load HTML and JS components via require

As you can see from the project structure diagram, there are two components defined in the Modules folder: Routet and title, and their template is an HTML file. Here's how this kind of component loads code:

Apt.acquire =function(path) {varArraypath; if(! This. IsArray (Path)) {Arraypath=[path]; }Else{Arraypath=path; }    varPromise = This. DFD (function(DFD) {require (Arraypath,function() {dfd.resolve (Array.prototype.slice.call (arguments)); },function(Error) {Dfd.reject (error);    });    }). Promise (); returnpromise;} Apt.createcomponent=function(componentname) {//can reload, read. vue files    varPath = This. $modulePrefix +componentname, HTML= ' text! ' + path + '/index.html ', JS= path + '/index.js ', Self= This; varPromise = This. Acquire ([Html,js]); Promise.done (function(Result) {varobj = result[1], content = result[0]; Obj.template=content; Obj.__path__=path;    Self. $components. push (obj);    }); returnpromise;}

Description: Acquire: Provides a way to load JS or HTML files via require and returns a promise, which makes it easier for callers to use them. Createcomponet: The corresponding JS and HTML files are located in the Modules folder based on the name of the call, and then the acquire loading component is called.

V. Main.js is quoted in this way

Provides methods for registering global components

Apt.registerglobalcomponents =function(componentnames) {varGloadcomponet = componentnames, self = This; varPromises = Gloadcomponet.map (function(data,index) {returnself.createcomponent (data);    }); varDFD = This. DFD (); $.when.apply (NULL, promises). Done (function(){        var_router = []; Self. $components. ForEach (function(Data,index) {self.Vue.component (data.name, data); _router.push ({path:'/' +data.name, component:data});        }); Self.router.addRoutes (_router); //Global registrations are registered as routesdfd.resolve (_router);    }); returndfd.promise ();}

References in the Main.js

var_app =App.createapp (); _app.registerglobalcomponents ([' title ', ' Route ']). Done (function(){    varVue =_app.createvue (); varCXT =App.getvue (). Createcontext (); varR ={state: {childs: []}, mutations: {childs:function(State, data) {State.childs=data; }}, actions: {childs:function(State, data) {State.commit (' Childs ', data); }}} vue. $store. Registermodule (' Router ', R); Vue. $mount (' #app ');});

Description

    1. Create an instance of the app;
    2. Register the Global components: title, route;
    3. Create a Vue instance after registration, and inject a two-level routing module into the Vuex of the instance

Requirejs, Vue, Vuex, Vue-route, do you think that it is feasible?

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.