我们不能处理来自可组合函数的数据



在我的例子中,我想检查用户是否通过stripe和firebase订阅了我的产品。

为了对其进行归档,我编写了一个可组合函数,用于检查firebase集合中的当前订阅。当用户有一个正在运行的订阅时,可组合函数应该返回数据,如果没有订阅,它应该返回null

我的问题是,当我在我的价值组件调用可组合函数,我不能使用返回的数据,因为它总是返回null。当我做console.log(subscription.value)时,我得到了可组合函数内部的正确值,但null在我的价值组件中。

我如何访问我的数据内部的值组件?

可组合函数

import { ref } from "vue";
import { db, auth } from "../../firebase/config";
import { collection, query, where, getDocs } from "firebase/firestore";
export function useCurrentSubscription() {
const isLoading = ref(false);
const subscription = ref(null);
const subscriptionType = ref(null);
async function fetchSubscription() {
isLoading.value = true;
const subRef = collection(
db,
"stripe-customers",
auth.currentUser.uid,
"subscriptions"
);
const subQuery = query(
subRef,
where("status", "in", ["trialing", "active", "past_due", "unpaid"])
);
await getDocs(subQuery).then((sub) => {
if (sub.docs.length > 0) {
subscription.value = sub.docs[0];
} else {
subscription.value = null;
}
});
if (subscription.value != null) {
var test = subscription.value.data();
subscriptionType.value = test.items[0].price.product.metadata.plan;
}
isLoading.value = false;
console.log(subscription.value) //returns the right data
}
fetchSubscription();
return { subscription, isLoading, subscriptionType };
}

value组件:

<template>
Help World
<template>
<script setup>
import SubscriptionPlansComponent from "../../components/subscriptionPlanComponents/SubscriptionPlansComponent.vue";
import CustomerPortalComponent from "../../components/subscriptionPlanComponents/CustomerPortalComponent.vue";
import { useCurrentSubscription } from "../../composables/stripe/currentSubscription";
const { subscription, isLoading, subscriptionType } = useCurrentSubscription();
console.log(subscription.value); //returns null all the time
</script>

可组合立即返回subscription,但实际数据是在解析异步函数fetchSubscription()时设置的。在此之前记录值,因此得到null。一切似乎都井然有序。

无论如何,您都必须使用某种加载机制。要么直接将其构建到组件中,然后使用已经返回的isLoadingref。或者你也可以改变你的可组合物来返回承诺,并使用内置的悬念,这将使Vue在呈现组件之前等待承诺解决。

下面的代码片段展示了如何将suspense与异步组件和可组合组件一起使用:

const { createApp, ref } = Vue;
const useAsyncComposable = function(){
const text = ref('not loaded')
const load = async () => text.value = await new Promise(resolve => setTimeout(() => resolve('composable has finished loading'), 3000))
const promise = load()
return {text, promise}
}
const AsyncComponent = {
template: '<div>{{ text }}</div>',
async setup(props, { attrs, slots, emit, expose }) {
const {text, promise} = useAsyncComposable()
await promise
return {text}
}
}
const App = { 
components: { AsyncComponent },
}
const app = createApp(App)
app.mount('#app')
<div id="app">
<suspense>
<template #default>
<async-component />
</template>

<template #fallback>
<div>Suspense fallback while waiting for async component</div>
</template>

</suspense>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

最新更新