Vue自定义hooks,从入门到精通😂

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 };
}

Vue自定义hooks,从入门到精通😂

https://cctv3.net/static/20241122/vue-use-hooks.html

作者

陈桥驿站

发布于

2024-11-22

更新于

2024-11-22

许可协议

评论