Require.js+vue Develop micro-letter upload image Components _javascript tips

Source: Internet
Author: User

As the project is thinkphp to do back-end framework, has been a multiple page of the back-end route, want to use the fiery webpack a bit out of the way (forgive me too much food, and promote Vue only I am a person ... , there is no way to use the Vue, only on the original basis of improvement. The great benefit of using Webpack is that you can use a single file such as. Vue to write Vue components, so that each component is a. vue file, where this component is introduced, and maintenance is really cool. However, the project has always been require.js, that is to organize Vue components in such a form, but also to add vue-router and Vue-resource, how to break? This article with the development of micro-letter upload image Components For example to summarize the Require.js+vue+vue-router+vue-resource development process.

Use Require.js to organize your components
We will have a components directory to put our various components, each component with its own name of the folder, such as the example of this album component, which is placed in this component of HTML, JS, CSS, Concrete how to use Require.js to load HTML and CSS, everyone baidu to download the relevant plug-ins. So the component JS can be in the define to load the relevant dependencies, and finally the component return, other components can also be loaded through the Define component, which also achieved the purpose of modular management components.

Here, I summed up a use of require.js to write Vue components of the template, use Webstorm to add this template, each time you write the components of a few words on the template generated, don't be too cool ah! (ComponentName is the template's variable, the template is generated so you can fill in your component name.)

Define (["Vue", "Text!.. /js/lib/components/$componentName $/index.html "," CSS!.. /js/lib/components/$componentName $/index.css "],function (vue,template) {
 ///Here is the code for the module
 var $componentName $ = Vue.extend ({
  template:template,
  props: [],
  data:function () {return
   {

   }
  },
  //At compile end and $ El ready:function () {} is called after the first time the document is inserted

  ,
  //Called when the instance is started to destroy. The instance still has functionality at this time.
  beforedestroy:function () {

  },
  methods: {

  },
  events: {

  }
 });
 return $componentName $;
});

Overall Preview This example
in order to demonstrate the complete process, I made this example a small single page called Show-album, on two pages:
1. The homepage is called Main-page

2. The details page is called Detail-page

The features in the details page are:

Receives the parameters passed by the parent component to upload the image component initialization
Click on the fork in the top right corner of each picture to delete the picture
Click on the last small camera logo call micro-letter "from the mobile Phone album map Interface", users can choose their own mobile phone map
When the picture is selected, the picture is scaled to a thumbnail as shown in the figure
Click the corresponding picture to call the micro-letter "Preview picture Interface" for a picture preview
When the picture is equal to the maximum number of pictures, the last small camera pattern disappears
Exposes two methods for other components to invoke ① upload image method (upload to the micro-trust server and perform the callback after successful uploading) Uploadimage② get all the image information methods, including initializing albums, deleted, new picture information getallimginfo

OK, Introduction finished, now officially start!

A. Use Vue-router to do the routing, build Show-album.js
the entire function called Show-album, so this function of JS we renamed to Show-album.js, this JS structure is this:

Define (["Vue", "Vueresource", "Vuerouter", "Valbum"],function (vue,vueresource,vuerouter,album) {//Install resource Module Vue.use (
  Vueresource);
  Install the Routing module Vue.use (vuerouter); jquery sets the Content-type to application/x-www-form-urlencoded when it executes a POST request, and//so the server resolves correctly, and when the native Ajax request is used,
  If the settings do not appear Content-type, then the default is Text/plain,//Then the server does not know how to parse the data, so only by getting the original data stream to parse the request data.
  Since Vue is using a native post, it is necessary to set up the server to properly interpret the data Vue.http.options.emulateJSON = True of the post past; Define MainPage page var mainPage = vue.extend ({Template: "#main-page-temp"})//define Detailpage page var detailpage = Vu E.extend ({Template: "#detail-page-temp", components: {' album ': Album}})//root component var showalbum = V  Ue.extend ({components: {' main-page ': mainPage, ' detail-page ': Detailpage}})//instantiate route VAR router
  = new Vuerouter (); Configure routing Router.map ({'/main-page ': {name: ' MainPage ', component:mainpage},//) use the dynamic fragment of the route '/deta Il-page/:inspection_id/:image_type ': {NAMe: ' Detailpage ', Component:detailpage}});
  Router.redirect ({//redirect any unmatched path to/home ' * ': '/main-page '});
  Starting the Apply//router creates an instance and mounts to the element on which the selector matches. 
Router.start (Showalbum, ' #show-album ');

 });

The HTML side is simple:

<template id= "Main-page-temp" >
 <group>
  <cell v-for= "list in lists"
     title= "Test" value= "click"
     is-link
     v-link= "{' name ': ' Detailpage ', params: {' inspection_id ': list.inspection_id, ' image_type ': List.image_type}} ">
  </cell>
 </group>
</template>

<template id=" Detail-page-temp ">
  <album v-ref:album:img-srcs=" Initimgsrcs "></album>
  <button style= "width:100%;margin-top:20px"
  Click I trigger Getallimginfo method
  </button>
</template>

< Div id= "Show-ablum" >
 <!--routing outside the chain-->
 <router-view></router-view>
</div>

Now click on a record on the home page, you can jump to the details page, back to the details page, you will return to the home page. So the overall structure is complete.

Two. Develop micro-letter upload image components

The specific code is not listed, we will follow the above component function list, say how each function to complete

1. Receive the parameters from the parent component to upload the image component initialization
First, set up the props in a subassembly.

Props: {
 ////Initialize photo
 Imgsrcs: {
  type:array, default
  : []
 },//
 whether to edit defaults true
 CanEdit: {
  Type:boolean,
  default:true
 },
 //maximum upload number default 9
 maxnum: {
  type:number,
  default:9
 },< c16/>//post-Upload callback
 afterupload: {
  type:function
 }
}

Then pass the parameters in the parent component when using the subassembly

<album v-ref:album 
: img-srcs= "Initimgsrcs": 
canedit= "true"
: afterupload= "Afteruploadfunction"
>
</album>

2. Click on the last small camera pattern call micro-letter "from the mobile Phone album map Interface", users can choose their own mobile phone map
Bind the Chooseimage method @click= "Chooseimage" in the HTML of the small camera pattern

<span class= "Add-img-icon" >
  
 </span>

The method is then added to the methods to select the image interface via Wx.chooseimage request micro-letters. JS-SDK need to be configured before using a micro-letter, so we can configure it when the component is ready.

Ready:function () {
   //configure micro-letter Js-sdk
   this.getsignpackage ();
  },
methods: {
 chooseimage:function () {
  var _this = this;
  Wx.chooseimage ({
   count: _this.maxnum-_this.albums.length,//Default 9
   sizetype: [' original ', ' compressed '],// You can specify whether the original or the compression diagram, the default both have
   sourcetype: [' album ', ' Camera '],//can specify whether the source is an album or a camera, both of which have
   success:function (res) {
    var _localids = res.localids;
    Record new photo info for
    (var i = 0,len = _localids.length;i < Len;i + +) {
     _this.newimagescache.push (_localids[i]); c16/>}
    //proportional generation of thumbnails
    _this.renderimage (_localids);}
   }
  );
}

3. After the selection of the picture, the picture proportionally adjusts the size to become as shown in the thumbnail image
Here to use the image preprocessing, that is, the var img = new Image (), by instantiating an image instance to obtain the size of the original, we can calculate the corresponding proportional thumbnail according to the original size. Specifically, this is true:

var img = new Image ();
var $albumSingle = "";
The order here is first new image (), then execute IMG.SRC, then the picture will be loaded to complete
//So the last call to the OnLoad method
img.onload = function () {
 Albumsdata = {
  localid:imgsrcs[i],
  albumsinglestyle: {height:imgwrapwidth + "px"},
  //compressimage is the method of compressing the picture, The picture instance and the width of the picture parent element are passed in to compute.
  Imgelementstyle: _this.compressimage (img,imgwrapwidth)
 };
 _this.albums.push (Albumsdata);
};
IMG.SRC = Imgsrcs[i];

Special attention to a place: because each picture has its own size style, so we're going to add a albums data in the component's data option as a photo dataset that contains each photo's own path and style, so that each picture will be mapped to its own properties when the loop renders each one. There is also, because the same picture can be repeated upload, so the loop to add track-by= "$index"

Each picture has its own attributes
Albumsdata = {
 localid:imgsrcs[i],
 albumsinglestyle: {height:imgwrapwidth + "px"},
 Compressimage is the method of compressing the picture, which is calculated by passing the picture instance and the width of the picture's parent element.
 Imgelementstyle: _this.compressimage (img,imgwrapwidth)
};
Put the attributes of each picture into the albums DataSet
_this.albums.push (Albumsdata);

4. Click the corresponding picture call micro-letter "Preview picture interface" for picture preview

Bind a hit event in the picture and pass in the index of the picture to trigger a method:

Previewimage:function (index) {
 var _albums = this.albums;
 var urls = this.getlocalids (_albums);
 Wx.previewimage ({
  current:urls[index],//////The HTTP link for the currently displayed picture
  Urls:urls   //The picture you want to preview HTTP link list
});

5. Click on the fork in the top right corner of each picture to delete the picture
This is a fixed-point hit on the fork, this event to handle the delete picture.

<i class= "Close-icon" @click = "DeleteImage ($index, album)" v-if= "CanEdit" ></i>

DeleteImage method, because you want to record the user deleted which initialization pictures, so to delete the image to determine if it is not initialized when the:

Deleteimage:function (index,album) {
 //Compare whether the photo you want to delete is in the initialization photo for
 (var i = 0,len = This.oldimagescache.length;i < Len;i + +) {
  if (Album.localid = = _oldimagescache[i]) {
   This.deleteImagesList.push (_oldimagescache[index));
  }
 this.canedit && this.albums. $remove (album);
}

6. When the picture equals the maximum number of pictures, the last small camera pattern disappears v-if= "Albums.length < 9"

7. Exposing two methods for other components to invoke ① upload image method (upload to the micro-trust server and perform the callback after successful uploading) Uploadimage② get all the image information methods, including initializing albums, deleted, new picture information getallimginfo
How to expose the method for other component calls is a big problem. I don't know how to do the best practice, because there are a variety of things, such as subassembly $dispatch, then the parent component in the events to receive, but this seems to be very cumbersome, so I chose to do this:
To add the component index using V-REL:XXX in a subassembly

<album v-ref:album:img-srcs= "Initimgsrcs" ></album>

this. $refs. Xxx.uploadimage () is then passed through the parent component to invoke the method exposed by the child component

This article has been organized into the "JavaScript micro-Credit Development Skills Summary", welcome to learn to read.

For everyone to recommend now more attention than the micro-letter Program Tutorial: "Micro-letter Small Program Development tutorial" Small series for everyone carefully organized, hope like.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.