


Using require.js+vue to develop WeChat upload image component method
This article mainly introduces the development of WeChat upload image component using require.js+vue+vue-router+vue-resource in detail. It has certain reference value. Interested friends can refer to it
Since the project is thinkPHP as the back-end framework, it has always been a multi-page back-end routing. I want to use the hot webpack and it is a bit difficult to start (forgive me for being too naive, and I am the only one promoting Vue...), there is no way, If you want to use Vue, you can only improve on the original basis. The huge benefit of using webpack is that you can use a single file like .vue to write vue components, so that each component is a .vue file. This component can be imported wherever it is used. It is really fun to maintain. However, the project has always used require.js. If I want to organize vue components in this form and add vue-router and vue-resource, how can I break it? This article uses the development of the WeChat upload image component as an example to summarize the development process of require.js+vue+vue-router+vue-resource.
Use require.js to organize your components
We will have a components directory to store our various components. Each component has its own folder named, such as the album component in this example. Just put the html, js, and css of this component. How to use require.js to load html and css? You can just download the relevant plug-ins from Baidu. Therefore, in the js of the component, all relevant dependencies can be loaded in define, and finally the component is returned. Other components can also load this component through define, which also achieves the purpose of modular management of components.
Here, I summarized a template for using require.js to write vue components. I used WebStorm to add this template and hit it every time I write a component. Don’t be too excited to generate a template with just a few words! (componentName is a variable of the template. You just need to fill in your component name when the template is generated)
define(["vue","text!../js/lib/components/$componentName$/index.html","css!../js/lib/components/$componentName$/index.css"],function (Vue,Template) { // 这里是模块的代码 var $componentName$ = Vue.extend({ template : Template, props : [], data : function() { return { } }, // 在编译结束和 $el 第一次插入文档之后调用 ready : function() { }, // 在开始销毁实例时调用。此时实例仍然有功能。 beforeDestroy : function() { }, methods : { }, events : { } }); return $componentName$; });
Overall preview of this example
For To demonstrate the complete process, I made this example into a small single page called show-album, with only two pages:
1. The homepage is called main-page
2. The details page is called detail-page
The functions in the details page are:
Receive the parameters passed by the parent component. Initialization of the upload picture component
Click the cross in the upper right corner of each picture to delete the picture
Click on the last small camera icon to call WeChat's "Picture Selection Interface from Mobile Album", users can select pictures on their mobile phones
After selecting the picture, the picture will be resized proportionally to become a thumbnail as shown in the picture
Click the corresponding picture to call the WeChat "Preview Picture Interface" for picture preview
When the picture is equal to the maximum number of pictures, finally The small camera pattern disappears
, exposing two methods for other components to call ①Upload image method (upload to WeChat server and execute callback after successful upload) uploadImage ②Get all image information method, including initializing the album, deleted , the new picture information getAllImgInfo
OK, the introduction is complete, now it officially begins!
1. Use vue-router for routing and build show-album.js
The entire function is called show-album, so we renamed the js of this function to show-album. js, the structure of this js is like this:
define(["vue","vueResource","vueRouter","vAlbum"],function (Vue,VueResource,VueRouter,Album) { // 安装资源模块 Vue.use(VueResource); // 安装路由模块 Vue.use(VueRouter); // jquery在执行post请求时,会设置Content-Type为application/x-www-form-urlencoded, // 所以服务器能够正确解析,而使用原生ajax请求时,如果不显示的设置Content-Type,那么默认是text/plain, // 这时服务器就不知道怎么解析数据了,所以才只能通过获取原始数据流的方式来进行解析请求数据。 // 由于vue是使用原生POST,所以要设置一下服务器才能正确解释POST过去的数据 Vue.http.options.emulateJSON = true; //定义mainPage页面 var mainPage = Vue.extend({ template : "#main-page-temp" }) //定义detailPage页面 var detailPage = Vue.extend({ template : "#detail-page-temp", components : { 'album' : Album } }) // 根组件 var showAlbum = Vue.extend({ components : { 'main-page' : mainPage, 'detail-page' : detailPage } }) // 实例化路由 var router = new VueRouter(); // 配置路由 router.map({ '/main-page' : { name : 'mainPage', component: mainPage }, //这里使用路由的动态片段 '/detail-page/:inspection_id/:image_type' : { name : 'detailPage', component : detailPage } }); router.redirect({ // 重定向任意未匹配路径到 /home '*': '/main-page' }); // 启动应用 // 路由器会创建一个实例,并且挂载到选择符匹配的元素上。 router.start(showAlbum, '#show-album'); });
It’s very simple on the HTML side:
<template id="main-page-temp"> <group> <cell v-for="list in lists" title="测试" value="点击" 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" 点击我触发getAllImgInfo方法 </button> </template> <p id="show-ablum"> <!-- 路由外链 --> <router-view></router-view> </p>
Now click on a record on the homepage to jump to the details page. On the details page If you go back, you will return to the home page. This completes the overall structure.
2. Develop WeChat upload image component
The specific codes will not be listed. Let’s talk about each one according to the above component function list. How to complete the function
1. Receive the parameters passed by the parent component to initialize the upload image component
First, set the props in the child component
props : { //初始化有无照片 imgSrcs : { type : Array, default : [] }, //是否可编辑 默认true canEdit : { type : Boolean, default : true }, //最大上传数 默认9 maxNum : { type : Number, default : 9 }, //上传后的回调 afterUpload : { type : Function } }
Then when using the child component in the parent component, just pass the parameters in
<album v-ref:album :img-srcs="initImgSrcs" :canEdit="true" :afterUpload="afterUploadFunction" > </album>
2. Click on the last small camera pattern to call WeChat's "Picture Selection Interface from Mobile Phone Album" , users can select images on their mobile phones
Bind the chooseImage method @click="chooseImage"
<span class="add-img-icon"> <img src="/static/imghw/default1.png" data-src="/cms/tpl/Index/Public/Home/source/image/camera.png" class="lazy" @click="chooseImage" alt="Using require.js+vue to develop WeChat upload image component method" > </span>
然后在methods中添加该方法,通过wx.chooseImage请求微信选择图片接口。使用微信js-sdk前需要配置,所以我们在组件的ready时就进行配置即可。
ready : function() { //配置微信JS-SDK this.getSignPackage(); }, methods : { chooseImage : function () { var _this = this; wx.chooseImage({ count: _this.maxNum - _this.albums.length, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { var _localIds = res.localIds; //记录新增照片信息 for (var i = 0,len = _localIds.length;i < len;i ++) { _this.newImagesCache.push(_localIds[i]); } //按比例生成缩略图 _this.renderImage(_localIds); } }); } }
3.选完图片后,图片按比例调整尺寸变成如图所示那样的缩略图
这里要使用到图片预处理,即var img = new Image ();通过实例化一个Image实例去获取原图的尺寸,我们才可以根据这个原图尺寸去计算出相应的等比例缩略图。具体是这样:
var img = new Image(); var $albumSingle = ""; //这里的顺序是先new Image(),然后执行img.src,完了之后图片才算装载完成 //这样最后才会调用onload方法 img.onload = function() { albumsData = { localId : imgSrcs[i], albumSingleStyle : {height : imgWrapWidth + "px"}, //compressImage是压缩图片的方法,将这个图片实例以及图片父元素的宽度传进去来计算。 imgElementStyle : _this.compressImage(img,imgWrapWidth) }; _this.albums.push(albumsData); }; img.src = imgSrcs[i];
特别注意的一个地方:由于每张图片的都有自己的尺寸样式,所以我们要在组件的data选项中添加一个albums的数据作为照片的数据集,里面包含每张照片自己的路径与样式,这样循环渲染每张图片时,才会每张图片对应自己的属性。还有就是,因为相同的图片可以重复上传,所以循环时要加上track-by=”$index”
//每张图片自己的属性 albumsData = { localId : imgSrcs[i], albumSingleStyle : {height : imgWrapWidth + "px"}, //compressImage是压缩图片的方法,将这个图片实例以及图片父元素的宽度传进去来计算。 imgElementStyle : _this.compressImage(img,imgWrapWidth) }; //将每张图片的属性都放到albums数据集里 _this.albums.push(albumsData);
4.点击相应的图片调用微信“预览图片接口”进行图片预览
在图片中绑定点击事件,传入该图片的索引,去触发一个方法:
previewImage : function (index) { var _albums = this.albums; var urls = this.getLocalIds(_albums); wx.previewImage({ current: urls[index], // 当前显示图片的http链接 urls: urls // 需要预览的图片http链接列表 });
5.点击每张图片右上角的叉叉可以删除图片
这个在叉上绑定点击事件,这个事件去处理删除图片。
deleteImage方法,由于要记录下用户删除了哪些初始化的图片,所以要在删除时判断一下这张图片是不是初始化时就有的:
deleteImage : function (index,album) { // 比较要删除的照片是否在初始化照片里 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.当图片等于最大图片数时,最后那个小相机图案消失 v-if=”albums.length
7.暴露出两个方法供别的组件调用①上传图片方法(上传到微信服务器并执行上传成功后的回调)uploadImage ②获取所有图片信息方法,包括初始化相册、删除过的、新增的图片信息getAllImgInfo
怎样暴露方法供别的组件调用,这是个大问题。我也不知道怎样做才是最佳实践,因为做法有多种,比如子组件$dispatch,然后父组件在events里接收一下,但这样好像很麻烦,于是我选择了这样做:
在子组件中使用v-rel:xxx添加该组件索引
然后在父组件里通过this.$refs.xxx.uploadImage()即可调用子组件暴露出来的方法
相关文章:
The above is the detailed content of Using require.js+vue to develop WeChat upload image component method. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

With the popularity of WeChat, more and more companies are beginning to use it as a marketing tool. The WeChat group messaging function is one of the important means for enterprises to conduct WeChat marketing. However, if you only rely on manual sending, it is an extremely time-consuming and laborious task for marketers. Therefore, it is particularly important to develop a WeChat mass messaging tool. This article will introduce how to use PHP to develop WeChat mass messaging tools. 1. Preparation work To develop WeChat mass messaging tools, we need to master the following technical points: Basic knowledge of PHP WeChat public platform development Development tools: Sub

In the development of WeChat public accounts, user tag management is a very important function, which allows developers to better understand and manage their users. This article will introduce how to use PHP to implement the WeChat user tag management function. 1. Obtain the openid of the WeChat user. Before using the WeChat user tag management function, we first need to obtain the user's openid. In the development of WeChat public accounts, it is a common practice to obtain openid through user authorization. After the user authorization is completed, we can obtain the user through the following code

As WeChat becomes an increasingly important communication tool in people's lives, its agile messaging function is quickly favored by a large number of enterprises and individuals. For enterprises, developing WeChat into a marketing platform has become a trend, and the importance of WeChat development has gradually become more prominent. Among them, the group sending function is even more widely used. So, as a PHP programmer, how to implement group message sending records? The following will give you a brief introduction. 1. Understand the development knowledge related to WeChat public accounts. Before understanding how to implement group message sending records, I

WeChat is currently one of the social platforms with the largest user base in the world. With the popularity of mobile Internet, more and more companies are beginning to realize the importance of WeChat marketing. When conducting WeChat marketing, customer service is a crucial part. In order to better manage the customer service chat window, we can use PHP language for WeChat development. 1. Introduction to PHP WeChat development PHP is an open source server-side scripting language that is widely used in the field of Web development. Combined with the development interface provided by WeChat public platform, we can use PHP language to conduct WeChat

In the development of WeChat public accounts, the voting function is often used. The voting function is a great way for users to quickly participate in interactions, and it is also an important tool for holding events and surveying opinions. This article will introduce you how to use PHP to implement WeChat voting function. Obtain the authorization of the WeChat official account. First, you need to obtain the authorization of the WeChat official account. On the WeChat public platform, you need to configure the API address of the WeChat public account, the official account, and the token corresponding to the public account. In the process of our development using PHP language, we need to use the PH officially provided by WeChat

How to use PHP to develop WeChat public accounts WeChat public accounts have become an important channel for promotion and interaction for many companies, and PHP, as a commonly used Web language, can also be used to develop WeChat public accounts. This article will introduce the specific steps to use PHP to develop WeChat public accounts. Step 1: Obtain the developer account of the WeChat official account. Before starting the development of the WeChat official account, you need to apply for a developer account of the WeChat official account. For the specific registration process, please refer to the official website of WeChat public platform

With the development of the Internet and mobile smart devices, WeChat has become an indispensable part of the social and marketing fields. In this increasingly digital era, how to use PHP for WeChat development has become the focus of many developers. This article mainly introduces the relevant knowledge points on how to use PHP for WeChat development, as well as some of the tips and precautions. 1. Development environment preparation Before developing WeChat, you first need to prepare the corresponding development environment. Specifically, you need to install the PHP operating environment and the WeChat public platform
