uni-helper / vite-plugin-uni-layouts

为 Vite 下的 uni-app 提供类 nuxt 的 layouts 系统
MIT License
25 stars 6 forks source link

layout中能否暴露出方法给子组件使用 #15

Closed kkfive closed 11 months ago

kkfive commented 11 months ago

描述问题

例如 在模板中定义一个 toast 组件,并将show方法暴露给子组件来调用

复现

<script setup lang="ts">
const toastRef= ref()

function showToast(data) {
  console.log('显示toast', data)
}

provide('showToast', showToast)
</script>

<template>
  <view class="px-10 py-20 text-center">
    <slot />
    <Footer />
    <view class="mx-auto mt-5 text-center text-sm opacity-25">
      [Default Layout]
    </view>
    <Toast ref="toastRef" />
  </view>
</template>

系统信息

。。。

使用的包管理器

pnpm

核对

KeJunMao commented 11 months ago
  1. 直接使用 provide/inject
  2. 使用可组合函数, 一份伪代码
    
    // useToast.ts
    const body = ref(null);
    export function useToastBody() {
    return body;
    }

export function useToast() { function add(_body) { body.value = _body; // your code... } function remove() { body.value = null; // your code... } return { add, remove, success: (body) => add({ type: "success", ...body }), error: (body) => add({ type: "error", ...body }), // more type alias... }; }


```vue
<!-- layouts/default.vue -->
<script setup>
const body = useToastBody();
</script>
<template>
  <div>
    <Toast :body="body" />
    <slot />
  </div>
</template>
<!-- pages/index.vue -->
<script setup>
const toast = useToast();
toast.add({
  // your code...
});
</script>
  1. 等我有空给 $refs 提供一个 ref,通过 this.$refs.layout 来访问 layout 中 defineExpose 提供的属性
KeJunMao commented 11 months ago

目前 DX 体验最好的应该是第二种方法,最方便的应该是第三种方法

kkfive commented 11 months ago

目前我通过在layout中把方法挂在给uni对象 可以实现 但是我觉得可以尝试下第二种 provide/inject 这个我尝试了下 好像不太行

KeJunMao commented 11 months ago

应该是可以的,正如 readme 所说的,layouts 插件不是魔法 :)