国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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

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

Mar 25, 2017 am 11:19 AM
WeChat development

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 {

   }
  },
  // 在編譯結(jié)束和 $el 第一次插入文檔之后調(diào)用
  ready : function() {

  },
  // 在開始銷毀實例時調(diào)用。此時實例仍然有功能。
  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

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在執(zhí)行post請求時,會設(shè)置Content-Type為application/x-www-form-urlencoded,
  // 所以服務(wù)器能夠正確解析,而使用原生ajax請求時,如果不顯示的設(shè)置Content-Type,那么默認是text/plain,
  // 這時服務(wù)器就不知道怎么解析數(shù)據(jù)了,所以才只能通過獲取原始數(shù)據(jù)流的方式來進行解析請求數(shù)據(jù)。
  // 由于vue是使用原生POST,所以要設(shè)置一下服務(wù)器才能正確解釋POST過去的數(shù)據(jù)
  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
   },
   //這里使用路由的動態(tài)片段
   '/detail-page/:inspection_id/:image_type' : {
    name : 'detailPage',
    component : detailPage
   }
  });
  router.redirect({
   // 重定向任意未匹配路徑到 /home
   '*': '/main-page'
  });
  // 啟動應(yīng)用
  // 路由器會創(chuàng)建一個實例,并且掛載到選擇符匹配的元素上。
  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="{&#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"
  點擊我觸發(fā)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
 },
 //最大上傳數(shù) 默認9
 maxNum : {
  type : Number,
  default : 9
 },
 //上傳后的回調(diào)
 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"

in the html of the small camera pattern
<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: [&#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);
   }
  });
 }
}

3.選完圖片后,圖片按比例調(diào)整尺寸變成如圖所示那樣的縮略圖
這里要使用到圖片預(yù)處理,即var img = new Image ();通過實例化一個Image實例去獲取原圖的尺寸,我們才可以根據(jù)這個原圖尺寸去計算出相應(yīng)的等比例縮略圖。具體是這樣:

var img = new Image();
var $albumSingle = "";
//這里的順序是先new Image(),然后執(zhí)行img.src,完了之后圖片才算裝載完成
//這樣最后才會調(diào)用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的數(shù)據(jù)作為照片的數(shù)據(jù)集,里面包含每張照片自己的路徑與樣式,這樣循環(huán)渲染每張圖片時,才會每張圖片對應(yīng)自己的屬性。還有就是,因為相同的圖片可以重復(fù)上傳,所以循環(huán)時要加上track-by=”$index”

//每張圖片自己的屬性
albumsData = {
 localId : imgSrcs[i],
 albumSingleStyle : {height : imgWrapWidth + "px"},
 //compressImage是壓縮圖片的方法,將這個圖片實例以及圖片父元素的寬度傳進去來計算。
 imgElementStyle : _this.compressImage(img,imgWrapWidth)
};
//將每張圖片的屬性都放到albums數(shù)據(jù)集里
_this.albums.push(albumsData);

4.點擊相應(yīng)的圖片調(diào)用微信“預(yù)覽圖片接口”進行圖片預(yù)覽Using require.js+vue to develop WeChat upload image component method

在圖片中綁定點擊事件,傳入該圖片的索引,去觸發(fā)一個方法:

previewImage : function (index) {
 var _albums = this.albums;
 var urls = this.getLocalIds(_albums);
 wx.previewImage({
  current: urls[index], // 當(dāng)前顯示圖片的http鏈接
  urls: urls   // 需要預(yù)覽的圖片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.當(dāng)圖片等于最大圖片數(shù)時,最后那個小相機圖案消失 v-if=”albums.length

7.暴露出兩個方法供別的組件調(diào)用①上傳圖片方法(上傳到微信服務(wù)器并執(zhí)行上傳成功后的回調(diào))uploadImage ②獲取所有圖片信息方法,包括初始化相冊、刪除過的、新增的圖片信息getAllImgInfo
怎樣暴露方法供別的組件調(diào)用,這是個大問題。我也不知道怎樣做才是最佳實踐,因為做法有多種,比如子組件$dispatch,然后父組件在events里接收一下,但這樣好像很麻煩,于是我選擇了這樣做:
在子組件中使用v-rel:xxx添加該組件索引

然后在父組件里通過this.$refs.xxx.uploadImage()即可調(diào)用子組件暴露出來的方法

相關(guān)文章:

分分鐘帶你玩轉(zhuǎn)Vue.js組件

圖文詳解Vue.js開發(fā)環(huán)境快速搭建方法

使用vue.js編寫好玩的拼圖小游戲?qū)嵗a

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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1500
276
PHP WeChat development: How to implement message encryption and decryption PHP WeChat development: How to implement message encryption and decryption May 13, 2023 am 11:40 AM

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.

PHP WeChat development: How to implement voting function PHP WeChat development: How to implement voting function May 14, 2023 am 11:21 AM

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

Using PHP to develop WeChat mass messaging tools Using PHP to develop WeChat mass messaging tools May 13, 2023 pm 05:00 PM

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

PHP WeChat development: How to implement customer service chat window management PHP WeChat development: How to implement customer service chat window management May 13, 2023 pm 05:51 PM

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

PHP WeChat development: How to implement user tag management PHP WeChat development: How to implement user tag management May 13, 2023 pm 04:31 PM

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

PHP WeChat development: How to implement group message sending records PHP WeChat development: How to implement group message sending records May 13, 2023 pm 04:31 PM

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

Steps to implement WeChat public account development using PHP Steps to implement WeChat public account development using PHP Jun 27, 2023 pm 12:26 PM

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

How to use PHP for WeChat development? How to use PHP for WeChat development? May 21, 2023 am 08:37 AM

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

See all articles