当前位置:网站首页>Compositionapi component development paradigm
Compositionapi component development paradigm
2022-07-19 14:49:00 【PY】
Code organization
Each contributor's code style is different , In identification CompositionAPI In the case of ideas . We hope to have a relatively standard code organization structure . Keep the overall code in a general code block style , The maintenance of components will be clearer , Avoid code accumulation .
A reasonable split
With upload Component as an example , Code blocks should be designed hierarchically . The first step is to split the components reasonably , The principle of splitting :
- Split sub components by presentation type :
uploadThere are many representation types of components , Therefore, it will derive 4 Sub components :Dragger、ImageCard、FlowList、SingleFile - Handle according to different logic , Gather different
hookLinked to presentation layer code :useComponentsStatus,useImgPreview,useRemove,useDragger,useActions.
Component state management
- Component parameter status , Bidirectional binding syntax , Controlled , Uncontrolled
- Context of a component's built-in state , Centrally manage the built-in status of components . Internal variables scattered in various code blocks are difficult to maintain . In this way, we can clearly know the built-in status of components . This part of the code can be passed
providerInject... Into a subcomponent , You can also usecontextPass .
matters needing attention
- Code like this short calculation is not very necessary
const isSingle = computed(() => props.theme === 'single')- Component event simplification , because
TDOfAPIUse in multiple frameworks , Will integrate somereact APIThe design of the , In terms of eventsXXX evntUsually accompanied byonXXXThe function parameter of , Component events - stay
options APIin ,methodsIt can be exposed directly , Unwantedexpose, andsetupin , Need on demandexposeCorrelation function . - Pay attention to the logical split , Don't write long code . High cohesion , Low coupling .
Component code example
import { defineComponent } from 'vue';
import { TdUploadProps } from './type'; _// The standard type file _
import props from './props'; _// The standard props file _
import { xxx } from './interface' _// If you need to customize some `interface`, Then put it into `interface` The file of _
_// Child components _
import Dragger from './dragger';
import ImageCard from './image';
import FlowList from './flow-list';
import SingleFile from './single-file';
_// hooks_
import { useConfig, usePrefixClass, useCommonClassName } from '../hooks/useConfig'; _// Overall config To configure , classPrefix, commonClass_
import useVModel from '../hooks/useVModel'; _// Grammar sugar and controlled processing _
import { useLogicHook } from './hook'; _// Inside components of pure logical code hook, Distinguish logically , Convenient subsequent maintenance _
export default defineComponent({
name: "TUpload",
props,
setup(props: TdUploadProps) {
const { classPrefix: prefix, global } = useConfig('upload');
const COMPONENT\_NAME = usePrefixClass('upload');
const { STATUS } = useCommonClassName();
const { files, modelValue } = toRefs(props);
_// `files` The updates of are used uniformly `setUploadValue`_
const [uploadValue, setUploadValue] = useVModel(
files,
modelValue,
props.defaultFiles || [],
props.onChange,
);
_// Component context , Centrally manage the built-in status of components _
const uploadCtx: UploadCtxType = reactive({
uploadValue,
setUploadValue,
loadingFile: null, _// Loading files _
toUploadFiles: [], _// File queue waiting to be uploaded _
errorMsg: '',
});
_// Logic layer `hook` Export the variables required by the presentation layer , dependent effect function ._
const { logicVar, logicHandler } = useLogicHook(props, uploadCtx)
_// The presentation layer `render` function , Split by module , Avoid the main problem `render` Too many functions ._
const renderContent = () => {
<div class={[COMPONENT\_NAME.value, {
STATUS.disabled: props.disabled
}]} onClick={logicHandler}>
{logicVar}
</div>
}
_// Can be directly in setup return render function , You don't need to write it alone `render` function . meanwhile `setup render` Function also has complete type support . Methods requiring external exposure can be used `ctx.expose`_
return () => (
<div>{renderContent()}</div>
)
},
})TNode Rendering
by TNode Of API in , Need to use useTNodeJSX Get the rendering function to render , It will be handled in the function propsfunction props Relationship with slot .
import { useTNodeJSX } from '../hooks/tnode';
defineComponent({
setup() {
const renderTNode = useTNodeJSX();
const renderChild = () => {
return renderTNode('default')
}
return () => (
<div>
// Two ways of writing
{renderTNode('TNodeName', options)}
{renderChild()}
</div>
)
},
})Component library configuration items
Unified use useConfig, useConfig It will export global, classPrefix, t.
In many cases, you may only need to export one belt prefix The name of the class , You can use usePrefixClass.
const COMPONENT\_NAME = usePrefixClass('componentName');
_// You can also get only one classPrefix_
const classPrefix = usePrefixClass();commonClass Some public class. It is divided into SIZE and STATUS.
const { SIZE, STATUS } = useCommonClassName()ConfigReceiverMixins Will be abandoned .
Bidirectional binding syntax , Controlled , Uncontrolled
Gradually abandon the use of higher-order functions mapProps. Realization v-model Use useVModel, Realization v-model:xx Use useDefaultValue. these two items. hook Internally, we will deal with controlled and uncontrolled , Use the exposed value inside the component , At the same time, external parameter updates also need to be updated with exposed functions .
useVModel
It is used to realize the bidirectional binding of main parameters v-model, Controlled and uncontrolled
import useVModel from '../hooks/useVModel';
const { value, modelValue } = toRefs(props)
const [innerValue, setInnerValue] = useVModel(
value,
modelValue,
props.defaultValue,
props.onChange,
'propsName' _// Optional parameters , Used for something like `files` This alias deals with the main two-way binding parameters _
);useDefaultValue
It is used to realize the bidirectional binding of auxiliary parameters v-model:visible, Controlled and uncontrolled
import useDefaultValue from '../hooks/useDefaultValue';
const { visible } = toRefs(props)
const [innerVisible, setInnerVisible] = useDefaultValue(
visible,
props.defaultVisible,
props.onVisibleChange,
'visible',
);Component events
stay TDesign vue There will be events in onXXX Of props function , Can pass props.onXXX To deal with . about props Events defined in do not need to be called emit('xxx').
_// props_
{
onChange?: (...args) => {};
}
_// tsx_
setup(props) {
props.onChange?.(args)
}Provide And inject
- The rational use of
ProvideAndinject, On demandprovide, avoidchildrencall$parentThis kind of code . - reasonable
InjectionKey, We need to pay attention toInjectionKeyExport location of , Avoid circular references .
import { InjectionKey } from 'vue';
const CheckboxGroupInjectionKey: InjectionKey<{
name: string;
componentProps: string,
xxxProvideProps: string,
}> = Symbol('componentName');边栏推荐
- Huawei wireless device configuration dynamic load balancing
- Problème de la valeur maximale de la fenêtre coulissante
- Pyside2嵌入Matplotlib的绘图
- 优秀的jar包启动shell脚本收藏
- Use tongweb's hot deployment function with caution
- Explain the operation of C language file in detail
- ShanDong Multi-University Training #3
- 实习是步入社会的一道坎
- MVCC多版本并发控制
- [port 3000 is already in use, solution to the problem of 3000 port being occupied]
猜你喜欢

Addition, deletion, modification and query of database

DMA方式的特点

Problème de la valeur maximale de la fenêtre coulissante

C speech Young's matrix · left-hand string · judge whether the string is rotated

中断的分类

End repeated development and personalize the login system in twoorthree times

Comparaison de deux types de machines virtuelles

ospf 附录 防环 重发布

Preview of authtalk phase I | comprehensive dismantling of multi tenant solutions

Database SQL Server
随机推荐
Codeforces Round #808 (Div. 1)(A~C)
C # read and write text and generate QR code
The first step of agile: turn "iteration" into "sprint" and start!
Redis
OSPF appendix anti ring Reissue
ShanDong Multi-University Training #3
Deployment principle
Oracle - 锁
C. Watto and mechanism (hash | dictionary tree + DFS (DFS on tree))
44、使用OrienMask进行实例分割目标检测,并进行mnn部署和ncnn部署
Win10 Microsoft Store打不开(开启TLS 1.2)
数据填报、报表展示哪家强?亿信ABI给你答案
[Axi] interpret the additional signals of the Axi protocol (QoS signal, region signal, and user signal)
MySQL index (III)
抽象类与派生类
Redis source code and design analysis -- 3 Dictionaries
单片机软件定时器V2.0
Li Kou 455 distribute cookie notes
MySQL read / write separation
Encrypt Ogg users