const hooks = []
export function addHook (hook) {
hooks.push(hook)
}
export function runHooks (context) {
return hooks.filter(hook => hook.condition(context))
.map(hook => hook.callback(context))
}
export function withHooks (func, context) {
return (...args) => {
console.log(args)
const result = func(...args)
if (result.then) {
result
.then(payload => runHooks({ ...context, payload }))
.catch(error => runHooks({ ...context, error }))
return result
}
runHooks({ ...context, payload: result })
return result
}
}
複製代碼
import { addHook } from '@/utils/hooks'
const CONTACT_FORM = 'contact-form.post'
addHook({
condition ({ error, id }) {
return !error && id === CONTACT_FORM
},
callback (context) {
// 用於數據報送、或數據分析的邏輯
console.log('用於數據報送、或數據分析的邏輯', context)
}
})
複製代碼
能夠看到咱們添加了一個新的Hook,只有在沒有錯誤而且id context參數與CONTACT_FORM id匹配時纔會觸發。在callback()函數中,咱們一般會在咱們選擇的跟蹤服務中觸發一個事件,但由於這只是一個演示,咱們只需觸發一個console.log()vue
模擬後臺請求 loanApply.js編程
export function post (data) {
return Promise.resolve(data)
}
複製代碼
<template>
<form @submit.prevent="submit">
<label class="contact-form-label">
Name
<input v-model="data.name">
</label>
<label class="contact-form-label">
Message
<textarea v-model="data.message"/>
</label>
<button>Submit</button>
</form>
</template>
<script>
import './tracking'
import { post } from '@/api/loanApply'
import { withHooks } from '@/utils/hooks'
export default {
data () {
return { data: { name: '', message: '' } }
},
methods: {
submit () {
withHooks(this.test, { id: 'contact-form.post' })(this.data)
},
async test (param) {
const {message, name} = await post(param)
console.log(message, name, '處理表單自己的業務邏輯')
return param
}
}
}
</script>
複製代碼