


Detailed explanation on adding mixin extensions in WeChat applet development
Mixin is an idea that uses partially implemented interfaces to achieve code reuse. It can be used to solve the problem of multiple inheritance and can be used to extend functions. The following article mainly introduces you to the relevant information about adding mixin extensions to WeChat mini programs. Friends in need can refer to it. Let’s take a look together.
Introduction to Mixin
Mixin (weaving) mode is not one of GOF’s “Design Patterns” summary, but it is used in various Languages and frameworks will find some application of this pattern (or idea). Simply put, Mixin is an interface with full or partial implementation, and its main function is better code reuse.
The concept of Mixin is supported in React and Vue. It provides convenience for us to abstract business logic and code reuse. However, the native mini program framework does not directly support Mixin. Let’s first look at a very practical requirement:
Add a running environment class to all mini program pages to facilitate some style hacks. Specifically, when the mini program is run in different operating environments (Developer Tools|iOS|Android), the platform value is the corresponding operating environment value ("ios|android|devtools")
<view class="{{platform}}"> <!--页面模板--> </view>
Reviewing the use of mixin in vue
The problems mentioned at the beginning of the article are very suitable to be solved using Mixin. We converted this requirement into a Vue problem: add a platform style class to each routing page (although this may not be practical). The implementation idea is to add a data: platform
to each routing component. The code is implemented as follows:
// mixins/platform.js const getPlatform = () => { // 具体实现略,这里mock返回'ios' return 'ios'; }; export default { data() { return { platform: getPlatform() } } }
// 在路由组件中使用 // views/index.vue import platform from 'mixins/platform'; export default { mixins: [platform], // ... }
// 在路由组件中使用 // views/detail.vue import platform from 'mixins/platform'; export default { mixins: [platform], // ... }
In this way, in the index and detail routing pages The viewModel has the platform value, which can be used directly in the template.
mixin classification in vue
data mixin
- ##normal method mixin
- lifecycle method mixin
export default { data () { return { platform: 'ios' } }, methods: { sayHello () { console.log(`hello!`) } }, created () { console.log(`lifecycle3`) } }
Mixin merging and execution strategies in vue
If there are duplications between mixins, these mixins will have specific merging and execution strategies. As shown below:How to make the applet support mixin
In front, we reviewed vue Knowledge about mixins. Now we need to make the mini program also support mixin and realize the same mixin function in vue.Implementation ideas
Let’s first take a look at the official mini program page registration method:Page({ data: { text: "This is page data." }, onLoad: function(options) { // Do some initialize when page load. }, onReady: function() { // Do something when page ready. }, onShow: function() { // Do something when page show. }, onHide: function() { // Do something when page hide. }, onUnload: function() { // Do something when page close. }, customData: { hi: 'MINA' } })
Page({ mixins: [platform], data: { text: "This is page data." }, onLoad: function(options) { // Do some initialize when page load. }, onReady: function() { // Do something when page ready. }, onShow: function() { // Do something when page show. }, onHide: function() { // Do something when page hide. }, onUnload: function() { // Do something when page close. }, customData: { hi: 'MINA' } })
There are two points here that we should pay special attention to:
Page(configObj)
- Configure the data, method, lifecycle, etc. of the applet page through configObj
- onLoad method - page main entrance
Page(). In fact,
Page(configObj) is an ordinary function call. We add an intermediate method:
Page(createPage(configObj))
Page() . This is the idea of implementing mixins.
Specific implementation
The specific code implementation will not be described in detail. You can see the following code. For more detailed code implementation, more extensions, and tests, please refer to github/** * 为每个页面提供mixin,page invoke桥接 */ const isArray = v => Array.isArray(v); const isFunction = v => typeof v === 'function'; const noop = function () {}; // 借鉴redux https://github.com/reactjs/redux function compose(...funcs) { if (funcs.length === 0) { return arg => arg; } if (funcs.length === 1) { return funcs[0]; } const last = funcs[funcs.length - 1]; const rest = funcs.slice(0, -1); return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args)); } // 页面堆栈 const pagesStack = getApp().$pagesStack; const PAGE_EVENT = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage']; const APP_EVENT = ['onLaunch', 'onShow', 'onHide', 'onError']; const onLoad = function (opts) { // 把pageModel放入页面堆栈 pagesStack.addPage(this); this.$invoke = (pagePath, methodName, ...args) => { pagesStack.invoke(pagePath, methodName, ...args); }; this.onBeforeLoad(opts); this.onNativeLoad(opts); this.onAfterLoad(opts); }; const getMixinData = mixins => { let ret = {}; mixins.forEach(mixin => { let { data={} } = mixin; Object.keys(data).forEach(key => { ret[key] = data[key]; }); }); return ret; }; const getMixinMethods = mixins => { let ret = {}; mixins.forEach(mixin => { let { methods={} } = mixin; // 提取methods Object.keys(methods).forEach(key => { if (isFunction(methods[key])) { // mixin中的onLoad方法会被丢弃 if (key === 'onLoad') return; ret[key] = methods[key]; } }); // 提取lifecycle PAGE_EVENT.forEach(key => { if (isFunction(mixin[key]) && key !== 'onLoad') { if (ret[key]) { // 多个mixin有相同lifecycle时,将方法转为数组存储 ret[key] = ret[key].concat(mixin[key]); } else { ret[key] = [mixin[key]]; } } }) }); return ret; }; /** * 重复冲突处理借鉴vue: * data, methods会合并,组件自身具有最高优先级,其次mixins中后配置的mixin优先级较高 * lifecycle不会合并。先顺序执行mixins中的lifecycle,再执行组件自身的lifecycle */ const mixData = (minxinData, nativeData) => { Object.keys(minxinData).forEach(key => { // page中定义的data不会被覆盖 if (nativeData[key] === undefined) { nativeData[key] = minxinData[key]; } }); return nativeData; }; const mixMethods = (mixinMethods, pageConf) => { Object.keys(mixinMethods).forEach(key => { // lifecycle方法 if (PAGE_EVENT.includes(key)) { let methodsList = mixinMethods[key]; if (isFunction(pageConf[key])) { methodsList.push(pageConf[key]); } pageConf[key] = (function () { return function (...args) { compose(...methodsList.reverse().map(f => f.bind(this)))(...args); }; })(); } // 普通方法 else { if (pageConf[key] == null) { pageConf[key] = mixinMethods[key]; } } }); return pageConf; }; export default pageConf => { let { mixins = [], onBeforeLoad = noop, onAfterLoad = noop } = pageConf; let onNativeLoad = pageConf.onLoad || noop; let nativeData = pageConf.data || {}; let minxinData = getMixinData(mixins); let mixinMethods = getMixinMethods(mixins); Object.assign(pageConf, { data: mixData(minxinData, nativeData), onLoad, onBeforeLoad, onAfterLoad, onNativeLoad, }); pageConf = mixMethods(mixinMethods, pageConf); return pageConf; };
Summary
1 , This article mainly talks about how to add mixin support to small programs. The implementation idea is: preprocessing configObjPage(createPage(configObj))
Summarize
The above is the detailed content of Detailed explanation on adding mixin extensions in WeChat applet development. 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



With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

Mixin in Vue is a very useful feature. It can encapsulate some reusable code in a mixin object, and then use mixin to introduce it in the components that need to use these codes. This method greatly improves the reusability and maintainability of the code, especially in some repeated CRUD (add, delete, modify) operations. This article will introduce how to use mixins to implement CRUD operations in Vue. First, we need to understand how to create a

Mini program registration operation steps: 1. Prepare copies of personal ID cards, corporate business licenses, legal person ID cards and other filing materials; 2. Log in to the mini program management background; 3. Enter the mini program settings page; 4. Select " "Basic Settings"; 5. Fill in the filing information; 6. Upload the filing materials; 7. Submit the filing application; 8. Wait for the review results. If the filing is not passed, make modifications based on the reasons and resubmit the filing application; 9. The follow-up operations for the filing are Can.
