当前位置:网站首页>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')]
})
边栏推荐
- 2021 q3-q4 investigation report on the use status of kotlin multiplatform
- Microservice governance (nocas)
- Jmeter响应时间和tps监听器使用教程
- Investment forecast and development strategy analysis report of China's rural sewage treatment industry in 2022
- One click deployment of your own community forum
- 这两天搭建环境遇到的几个问题
- Question B of 2016 Sichuan Ti Cup Electronic Design Competition
- New routing file in laravel framework
- Lintcode 130 · 堆化
- Introduction to the four major FPGA manufacturers abroad
猜你喜欢

Spark-day03-core programming RDD operator

Loggie encoding and newline character test
![[graduation season · advanced technology Er] I remember the year after graduation](/img/e7/8e1dafa561217b77a3e3992977a8ec.png)
[graduation season · advanced technology Er] I remember the year after graduation

Laravel+gatewayworker completes the im instant messaging and file transfer functions (Chapter 4: server debugging errors)

Build Pikachu shooting range and introduction
女性科学家的流失
![[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test](/img/2f/f44381ea759f4c1c957a8f9434f0ee.png)
[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test

PHP uses laravel pay component to quickly access wechat jsapi payment (wechat official account payment)

Microservice governance (nocas)

New routing file in laravel framework
随机推荐
Scala-day06- pattern matching - Generic
China Medical Grade hydrogel market supply and demand research and prospect analysis report 2022 Edition
开通证券账户需要注意事项 开户安全吗
JS how to judge when data contains integer and floating-point types. Floating-point decimals retain two digits after the decimal point
redis通过6379端口无法连接服务器
PHP returns false when calling redis method decrby less than 0
Ad - update the modified PCB package to the current PCB
NFS shared storage service installation
证券账户可以开通 开户安全吗
Scala-day01- companion objects and HelloWorld
MS17_ 010 utilization summary
fastjson的JSONArray和JSONObject[通俗易懂]
Precautions for opening a securities account is it safe to open an account
这两天搭建环境遇到的几个问题
HUST网络攻防实践|6_物联网设备固件安全实验|实验二 基于 MPU 的物联网设备攻击缓解技术
2021 q3-q4 investigation report on the use status of kotlin multiplatform
[solved] data duplication or data loss after laravel paginate() paging
请指教同花顺是什么软件?在线开户安全么?
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure
Vscode solves the problem of Chinese garbled code