Vue
里面很有多蛋疼的地方,比如提交表单的时候,移动端和桌面端是两套 UI,但是操作的逻辑是一样的。尤其是比如表单是分步骤的,还得处理多个步骤,所以说得把业务封装成hooks
,两个端都能复用。
比较蛋疼的地方:
多个hooks
如何修改同一份store
hooks
如何引用组件的props
hooks
如何调用组件的emits
项目结构
对于hooks
如何修改同一份实力,需要定义一个单独的store --> useState()
import { ref, watch } from "vue"; import { PAGE, PageStack } from "../constants"; import { $t } from "@/i18n";
export function useState() { const stack = ref < PageStack > new PageStack([], 0); return { stack }; }
|
import { type Ref } from "vue"; import { ACTION, PAGE, PAGES, PageStack } from "../constants"; import { Router } from "vue-router";
export function useOP(stack: Ref<PageStack>) { const onPress = (e: { action: ACTION, params: any }) => { page.value = stack.value.current(); }; return { onPress }; }
|
坑
修改同一份store
注意这个地方在hooks
里面拿到的是store
里面的stack
的实例
const { stack } = useState(); const { onSelectMethod, onPress } = useOP(stack);
|
export function useOP(stack: Ref<PageStack>) { const onPress = (e: { action: ACTION, params: any }) => { page.value = stack.value.current(); }; return { onPress }; }
|
引用组件的props
这个地方传参的时候,要传递toRef(props, '...')
,比如我现在有一个intent
const props = defineProps(["show", "user", "intent"]); const { onSelectMethod, onPress } = useOP(stack, toRef(props, "intent"));
|
export function useOP(stack: Ref<PageStack>, intent: Ref<number>) { const onPress = (e: { action: ACTION, params: any }) => {}; return { onPress }; }
|
引用组件的emits
有时候需要在hooks
里面,通知组件,emits
注意ts
写法
const props = defineProps(['show', 'user', 'intent']) const emits = defineEmits(['onClose'])
const { page, stack, title, reset, nextParams } = useState() const { onSelectMethod, onPress } = useOP( stack, toRef(props, 'intent'), emits as (event: string, ...args: any[]) => void )
|
export function useOP( stack: Ref<PageStack>, intent: Ref<number>, emits: (event: string, ...args: any[]) => void ) { const onPress = (e: { action: ACTION, params: any }) => {}; return { onPress }; }
|