This article describes require in detail. js + vue-router + vue-resource has some reference value for developing and uploading image components. if you are interested, refer to this article for details about require. js + vue-router + vue-resource development and upload image components are of reference value. if you are interested, refer
Because thinkPHP is used as the backend framework for the project, it has always been a multi-page backend route, and it is a bit difficult to use the hot webpack (forgive me for being too good, and I am the only one who promotes vue ......), No way. to use vue, you can only improve it based on the original version. The biggest advantage of using webpack is that it can be used. A single file such as vue is used to write vue components, so that each component is. the vue file is introduced wherever this component is used. it is really easy to maintain. However, the project has been using require. js for a long time, so I want to organize vue components in this way, and add vue-router and vue-resource. how can this problem be solved? This article summarizes the development process of require. js + vue-router + vue-resource with the example of developing and uploading image components.
Use require. js to organize your components
We have a components directory for each component. each component uses a folder named by its own name. for example, the album component in this example contains the html, js, and css components of this component, how to use require. js loads html and css. you can download the relevant plug-ins from Baidu. Therefore, the js component can load the dependencies in define, and finally return the component. other components can also load the component through define, this also achieves the purpose of modular management components.
Define (["vue", "text !.. /Js/lib/components/$ componentName $/index.html "," css !.. /Js/lib/components/$ componentName $/index.css "], function (Vue, Template) {// the module code var $ componentName $ = Vue. extend ({template: Template, props: [], data: function () {return {}}, // call ready after compilation ends and $ el inserts the document for the first time: function () {}, // called when the instance is destroyed. The instance is still functional. BeforeDestroy: function () {}, methods :{}, events :{}}); return $ componentName $ ;});
General preview example
To demonstrate the complete process, I made this example into a small single page named show-album. There are two pages:
1. the home page is called main-page.
The whole function is called show-album, so the js of this function we renamed to show-album.js, the structure of this js is like this:
Define (["vue", "vueResource", "vueRouter", "vAlbum"], function (Vue, VueResource, VueRouter, Album) {// install the resource module Vue. use (VueResource); // install the route module Vue. use (VueRouter); // when jquery executes a post request, it sets Content-Type to application/x-www-form-urlencoded, // so the server can correctly parse the request, when a native ajax request is used, if the Content-Type is not displayed, the default value is text/plain. // then the server does not know how to parse the data, therefore, the request data can only be parsed by obtaining the original data stream. // Because vue uses native POST, you need to set the server to correctly interpret the previous POST data Vue. http. options. emulateJSON = true; // defines the mainPage var mainPage = Vue. extend ({template: "# main-page-temp"}) // defines the detailPage var detailPage = Vue. extend ({template: "# detail-page-temp", components: {'Album ': album}) // root component var showAlbum = Vue. extend ({components: {'main-page': mainPage, 'Detail-page': detailPage}) // instantiate the routing var router = New VueRouter (); // Configure the route router. map ({'/main-page': {name: 'mainpage', component: mainPage}, // use the dynamic route fragment here'/detail-page/: inspection_id /: image_type ': {name: 'detailpage', component: detailPage}); router. redirect ({// redirect any unmatched path to/home '*': '/main-page'}); // start the application // The vro creates an instance, and mounted to the elements that match the selector. Router. start (showAlbum, '# show-album ');});
HTML is simple:
Click a record on the home page to go to the details page. after the details page is displayed, it will return to the home page. This completes the overall structure.
2. develop and upload image components
The specific code is not listed. we will follow the component function list above to explain how each function is completed.
1. receive parameters passed by the parent component to initialize the uploaded image component.
First, set props in the child component.
Props: {// initialize whether there are photos imgSrcs: {type: Array, default: []}, // whether to edit default value: true canEdit: {type: Boolean, default: true }, // maximum Number of uploads 9 by default maxNum: {type: Number, default: 9}, // callback afterUpload: {type: Function} after Upload }}
Then, when the child component is used in the parent component, the parameter can be passed in.
2. click the last small camera pattern to call the "select image from mobile phone album" interface. you can select a picture on your mobile phone.
Bind the chooseImage method @ click = "chooseImage" to the html of the small camera pattern"
Then add this method to methods and use the wx. chooseImage request to select an image interface. Before using the js-sdk, you need to configure it. Therefore, you can configure it in ready of the component.
Ready: function () {// Configure the JS-SDK this. getSignPackage () ;}, methods: {chooseImage: function () {var _ this = this; wx. chooseImage ({count: _ this. maxNum-_ this. albums. length, // The default value is 9 sizeType: ['original', 'compressed ']. // you can specify the source image or a compressed image. by default, both of them have sourceType: ['alipay ', 'Camera '], // you can specify whether the source is an album or a camera. by default, both have success: function (res) {var _ localIds = res. localIds; // record new photo information for (var I = 0, len = _ localIds. length; I <len; I ++) {_ this. newImagesCache. push (_ localIds [I]);} // Generate a thumbnail in proportion _ this. renderImage (_ localIds );}});}}
3. after the image is selected, adjust the size of the image in proportion to that of the thumbnail.
Image preprocessing is used here, that is, var img = new Image (); the size of the source Image is obtained by instantiating an Image instance, we can calculate the proportional thumbnails based on the size of the source image. The details are as follows:
Var img = new Image (); var $ albumSingle = ""; // the order here is first new Image (), and then execute img. src. after the image is finished, it is regarded as loaded. // then the onload method img will be called. onload = function () {albumsData = {localId: imgSrcs [I], albumSingleStyle: {height: imgWrapWidth + "px"}, // compressImage is the method for compressing images, calculate the width of the image instance and its parent element. ImgElementStyle: _ this. compressImage (img, imgWrapWidth)}; _ this. albums. push (albumsData);}; img. src = imgSrcs [I];
Note: Because each image has its own size style, we need to add an albums data in the data option of the component as the photo dataset, it contains the path and style of each photo, so that each image corresponds to its own attribute only when it is cyclically rendered. In addition, because the same image can be uploaded repeatedly, track-by = "$ index" must be added to the loop"
// Attributes of each image albumsData = {localId: imgSrcs [I], albumSingleStyle: {height: imgWrapWidth + "px"}, // compressImage is used to compress the image, calculate the width of the image instance and its parent element. ImgElementStyle: _ this. compressImage (img, imgWrapWidth)}; // put the attributes of each image in the albums dataset _ this. albums. push (albumsData );
4. click the corresponding image and call "preview image" to preview the image.
Bind a click event to the image and input the image index to trigger a method:
PreviewImage: function (index) {var _ albums = this. albums; var urls = this. getLocalIds (_ albums); wx. previewImage ({current: urls [index], // The http link urls: urls // http link list of the image to be previewed });
5. click the cross button in the upper-right corner of each image to delete the image.
This event is bound to the click event on the cross, and the event is used to process and delete images.
The deleteImage method is used to record the initialized images deleted by the user. Therefore, when deleting the images, you must determine whether the images are available during initialization:
DeleteImage: function (index, album) {// compare whether the photo to be deleted is in the initial 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 image is equal to the maximum number of images, the last small camera pattern disappears v-if = "albums. length <9"
7. two methods are exposed for other components to call ① Upload image method (upload to the server and perform the callback after the upload is successful) uploadImage ② obtain all image information method, including initializing, deleting, and adding image information getAllImgInfo
How to expose methods for other components to call is a big problem. I don't know how to do it, because there are a variety of practices, such as the sub-component $ dispatch, and then the parent component receives it in the events, but it seems very troublesome, so I chose to do this:
Add the component index using v-rel: xxx in the child component
Then, you can use this. $ refs. xxx. uploadImage () in the parent component to call the method exposed by the child component.
Related articles:
Vue. js components
Quick building of Vue. js development environment
Use vue. js to compile the code of a fun puzzle game instance
The above describes how to use require. js + vue to develop and upload image components. For more information, see other related articles on php Chinese network!