Antd输入框卡顿及Pubsub.js使用问题怎么解决
项目场景
项目中通过表单来填写校验大量复杂数据
问题描述
项目中使用的是Ant Design of Vue这个组件库,使用FormModel 表单,数据字段和校验较多时,表单操作卡顿;eg: a-input输入框,等你输入完字及,几秒后才慢慢出现你输入的字符
原因分析
vue在进行输入时,进行了多次的render刷新渲染操作,导致了input框输入时发生的卡顿现象
解决方案
官方给出的解决办法,将 Form 相关的业务独立到一个单独的组件中,减少组件渲染的消耗,如果有很多校验项,可把它们分别放在不同的Form中处理
eg :
一、组件封装

将大表单拆分成三个组件表单,数据校验等操作在其组件内部实现
二、formTable中的字段有部分与formTableTwo联动
这里使用PubSub.js进行兄弟组件传值
PubSub.js的使用
1.首先安装pubsub-js
npm install --save pubsub-js
2.简单使用
导入
import PubSub from 'pubsub-js'
发送消息:
PubSub.publish(名称,参数)订阅消息:
PubSub.subscrib(名称,函数)取消订阅:
PubSub.unsubscrib(名称)
在formTableTwo中使用PubSub.publish(名称,参数)发送信息,formTableOne中使用PubSub.subscrib(名称,函数)接收信息。
注意:
1.PubSub.subscrib(名称,函数)接收信息的所传名称要与PubSub.publish(名称,参数)发送信息的名称一致
2.PubSub.subscrib(名称,函数)接收信息可能会被触发多次,可以在PubSub.subscrib(名称,函数)前使用 PubSub.unsubscribe可以解决
created () {
// console.log('form1', this.form)
// 解决PubSub多次调用
PubSub.unsubscribe('send');
// 订阅消息(接收消息)
PubSub.subscribe('send', (name, value) => {
console.log('name', name)
console.log('value', value)
})
// 订阅组件二的消息
PubSub.subscribe('sendTwo', (name, val) => {
console.log('sendTwo', name)
console.log('我是接受到的值', val)
this.isShow = val
})
console.log('this.form', this.form)
},3.记得发布了消息 要在vue beforedestory 中销毁取消订阅 ,发布的次数多了,会造成订阅一次触发多次的情况;
beforeDestroy () {
PubSub.unsubscribe('send')
PubSub.unsubscribe('sendTwo')
}三、使用Promise.all提交校验表单
子组件
onSubmit () {
return new Promise((resolve, reject) => {
this.$refs.ruleForm.validate(valid => {
if (valid) {
console.log('表单1通过')
this.outgoingInfo()
resolve(valid)
} else {
console.log('error submit!!')
reject(valid)
return false
}
})
})
},父组件
// 表单校验
submitForm () {
console.log('this.$refs.FormTableOne.form', this.$refs.FormTableOne.form)
const rules1 = this.$refs.FormTableOne.onSubmit()
const rules2 = this.$refs.FormTableTwo.onSubmit()
const rules3 = this.$refs.FormTableThree.onSubmit()
Promise.all([rules1,rules2, rules3]).then(() => {
console.log('校验通过')
})
},完整demo
formGroup
submit Reset
formTableOne
{ $refs.name1.onFieldBlur() } " /> Zone one Zone two Online Promotion Offline Sponsor Venue Create
formTabeTwo
{ $refs.name2.onFieldBlur() } " /> Zone one Zone two Online Promotion Offline Sponsor Venue
formTableThree
{ $refs.name3.onFieldBlur() } " /> Zone one Zone two Online Promotion Offline Sponsor Venue