当前位置:网站首页>Implementing mixins scheme in applet
Implementing mixins scheme in applet
2022-06-26 12:27:00 【C+ Ankou wood】
In the process of developing a native applet , It was found that several pages use almost the same logic . Because the applet official did not provide Mixins This code reuse mechanism , So we can only copy and paste in a very elegant way “ Reuse ” Code . As functions become more and more complex , It's obviously unscientific to maintain code by copying and pasting , So I thought about how to implement it in a small program Mixins.
What is? Mixins
Mixins It's literally “ Mix in ” It means , As the name implies, it is to mix reusable code into current code . be familiar with VueJS Our students should be clear about , It provides more powerful code reuse capabilities , Decoupled repetitive modules , Make system maintenance more convenient and elegant .
Take a look at first VueJS How to use Mixins Of .
// define a mixin object
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // => "hello from mixin!"
In the above code , First of all, I defined a name as myMixin The object of , It defines some life cycle functions and methods . Then directly through... In a new component mixins: [myMixin] Way of injection , At this point, the newly created component is obtained from myMixin The method of the .
Got it Mixins in the future , You can start to implement it in the applet .
Mixins The mechanism of
Mixins There are also some small details that need attention , It's about the sequence of life cycle events . In the example in the previous section , We are myMixin There is a definition of created() Method , This is a VueJS A life cycle event in it . If we are creating a new component Component It also defines a created() Method , So what's the result of the execution ?
var Component = Vue.extend({
mixins: [myMixin],
created: function () {
console.log('hello from Component!')
}
})
var component = new Component()
// =>
// Hello from mixin!
// Hello from Component!
It can be seen that the running result is output from Mixin Of log, And then output the log.
In addition to life cycle functions , Let's take a look at the blending results of the object properties :
// define a mixin object
const myMixin = {
data () {
return {
mixinData: 'data from mixin'
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin],
data () {
return {
componentData: 'data from component'
}
},
mounted () {
console.log(this.$data)
}
})
var component = new Component()

stay VueJS in , Will bring from Mixins And the object properties of the component ( Such as data, methods etc. ) blend , To ensure that both sides of the data exist at the same time .
After the above verification , We can get VueJS About China Mixins Conclusion of operation mechanism :
Lifecycle attribute , Priority will be given to execution from Mixins In the middle of , And then execute the... From the component .
Object type properties , come from Mixins And from the component will coexist .
But in the applet , This mechanism will work with VueJS There is a little difference between . In the applet , The custom method is defined directly in Page Of the attributes of , It's not a lifecycle type property , It's not an object type property either . In order not to introduce strange questions , We're for the applet Mixins One more operation mechanism :
Custom methods in applets , The priority for Page > Mixins, namely Page The custom method in will override Mixins In the middle of .
Code implementation
In the applet , Each page is composed of Page(options) Function definition , and Mixins So, what's going on in this function is options object . So we realize Mixins There is a way of thinking —— Hijack and rewrite Page function , Finally, release it again .
Create a new one mixins.js file :
// Preserve the original Page function
const originPage = Page
Page = (options) => {
const mixins = options.mixins
// mixins Must be an array
if (Array.isArray(mixins)) {
delete options.mixins
// mixins Inject and execute the corresponding logic
options = merge(mixins, options)
}
// Release native Page function
originPage(options)
}
The principle is simple , The key is merge() function .merge Functions are applets Mixins Specific implementation of operation mechanism , Follow the three conclusions summarized in the previous section .
// Define the properties built into the applet / Method
const originProperties = ['data', 'properties', 'options']
const originMethods = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onPageScroll', 'onTabItemTap']
function merge (mixins, options) {
mixins.forEach((mixin) => {
if (Object.prototype.toString.call(mixin) !== '[object Object]') {
throw new Error('mixin Type must be object !')
}
// Traverse mixin All the attributes in it
for (let [key, value] of Object.entries(mixin)) {
if (originProperties.includes(key)) {
// Built in object properties blend in
options[key] = {
...value, ...options[key] }
} else if (originMethods.includes(key)) {
// Built in method properties blend in , Give priority to the mixed part
const originFunc = options[key]
options[key] = function (...args) {
value.call(this, ...args)
return originFunc && originFunc.call(this, ...args)
}
} else {
// Custom methods blend in
options = {
...mixin, ...options }
}
}
})
return options
}
Mixins Use
1、 In the applet app.js In the introduction mixins.js
require('./mixins.js')
2、 Write a myMixin.js
module.exports = {
data: {
someData: 'myMixin' },
onShow () {
console.log('Log from mixin!') }
}
3、 stay page/index/index.js Use in
Page({
mixins: [require('../../myMixin.js')]
})
边栏推荐
- Deep thinking from senior member managers
- 【概率论】条件概率、贝叶斯公式、相关系数、中心极限定理、参数估计、假设检验
- Lintcode 130 · stacking
- Five trends of member marketing of consumer goods enterprises in the future
- Comparison of latest mobile phone processors in 2020 (with mobile phone CPU ladder diagram)
- Leetcode 78. Subset and 90 Subset II
- Encapsulate request request of uni app
- Common problems and Thoughts on member operation management
- 7-2 大盗阿福
- 国际美妆业巨头押注中国
猜你喜欢

Laravel+gatewayworker completes the im instant messaging and file transfer functions (Chapter 4: server debugging errors)
![[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure](/img/d5/db1931596c26090092aaa065103dbb.png)
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure

国际美妆业巨头押注中国

"Pinduoduo and short video speed version", how can I roast!
![[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure](/img/d2/a6cbb0abe9e04c412d1f6021430528.png)
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure

Ad - update the modified PCB package to the current PCB

Spark-day01- get started quickly
![[solved] data duplication or data loss after laravel paginate() paging](/img/68/7bf51bbf893a91bee24f5f7d4a369f.jpg)
[solved] data duplication or data loss after laravel paginate() paging

International beauty industry giants bet on China

Laravel subdomain accesses different routing files and different modules
随机推荐
十大券商有哪些?手机开户安全么?
Ad - update the modified PCB package to the current PCB
[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test
环形队列php
MS17_ 010 utilization summary
The most complete kubernetes core command of the latest version so far
Five problems and solutions of member operation
2016年四川省TI杯电子设计竞赛B题
2022 edition of investment analysis and "fourteenth five year plan" development prospect forecast report of China's switchgear industry
The transformation of enterprise customers' digital assets needs to suit the case
Leetcode 78. 子集 and 90. 子集 II
SQL injection in Pikachu shooting range
Report on in-depth analysis and investment strategy recommendations for China's petroleum coke industry (2022 Edition)
Consumer goods enterprises, four pain points of member marketing
Fengshentai old shooting range Kali series
Five trends of member management in 2022
2022 edition of Beijing 5g industry investment planning and development prospect forecast analysis report
Laravel+gatewayworker completes the im instant messaging and file transfer functions (Chapter 4: server debugging errors)
一个初级多线程服务器模型
Example of parameter passing from laravel query constructor to closure method