Using require.js+vue to develop WeChat upload image component method

高洛峰
Release: 2017-03-25 11:19:07
Original
2722 people have browsed it

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.

Using require.js+vue to develop WeChat upload image component method

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$;
});
Copy after login

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

Using require.js+vue to develop WeChat upload image component method

2. The details page is called detail-page

Using require.js+vue to develop WeChat upload image component method

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'); 
});
Copy after login

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="{&#39;name&#39;:&#39;detailPage&#39;,params: { &#39;inspection_id&#39;: list.inspection_id,&#39;image_type&#39; : 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>
Copy after login

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
 }
}
Copy after login

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>
Copy after login

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"

in the html of the small camera pattern
<span class="add-img-icon">
  <img  src="/cms/tpl/Index/Public/Home/source/image/camera.png" @click="chooseImage" alt="Using require.js+vue to develop WeChat upload image component method" >
 </span>
Copy after login

然后在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: [&#39;original&#39;, &#39;compressed&#39;], // 可以指定是原图还是压缩图,默认二者都有
   sourceType: [&#39;album&#39;, &#39;camera&#39;], // 可以指定来源是相册还是相机,默认二者都有
   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);
   }
  });
 }
}
Copy after login

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];
Copy after login

特别注意的一个地方:由于每张图片的都有自己的尺寸样式,所以我们要在组件的data选项中添加一个albums的数据作为照片的数据集,里面包含每张照片自己的路径与样式,这样循环渲染每张图片时,才会每张图片对应自己的属性。还有就是,因为相同的图片可以重复上传,所以循环时要加上track-by=”$index”

//每张图片自己的属性
albumsData = {
 localId : imgSrcs[i],
 albumSingleStyle : {height : imgWrapWidth + "px"},
 //compressImage是压缩图片的方法,将这个图片实例以及图片父元素的宽度传进去来计算。
 imgElementStyle : _this.compressImage(img,imgWrapWidth)
};
//将每张图片的属性都放到albums数据集里
_this.albums.push(albumsData);
Copy after login

4.点击相应的图片调用微信“预览图片接口”进行图片预览Using require.js+vue to develop WeChat upload image component method

在图片中绑定点击事件,传入该图片的索引,去触发一个方法:

previewImage : function (index) {
 var _albums = this.albums;
 var urls = this.getLocalIds(_albums);
 wx.previewImage({
  current: urls[index], // 当前显示图片的http链接
  urls: urls   // 需要预览的图片http链接列表
});
Copy after login

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);
}
Copy after login

6.当图片等于最大图片数时,最后那个小相机图案消失 v-if=”albums.length

7.暴露出两个方法供别的组件调用①上传图片方法(上传到微信服务器并执行上传成功后的回调)uploadImage ②获取所有图片信息方法,包括初始化相册、删除过的、新增的图片信息getAllImgInfo
怎样暴露方法供别的组件调用,这是个大问题。我也不知道怎样做才是最佳实践,因为做法有多种,比如子组件$dispatch,然后父组件在events里接收一下,但这样好像很麻烦,于是我选择了这样做:
在子组件中使用v-rel:xxx添加该组件索引

然后在父组件里通过this.$refs.xxx.uploadImage()即可调用子组件暴露出来的方法

相关文章:

分分钟带你玩转Vue.js组件

图文详解Vue.js开发环境快速搭建方法

使用vue.js编写好玩的拼图小游戏实例代码

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template