【发布时间】:2021-06-07 03:07:08
【问题描述】:
我有一个自定义钩子,其中有一个本地状态: 但似乎,当我使用 toRefs() 导出状态并使用状态是另一个组件时,我收到错误消息:“Type 'Ref' is not assignable to type 'boolean'”
钩子:
interface StateModel {
isLoading: boolean;
isError: boolean;
errorMessage: string;
data: object | null;
}
export default function useAxios(url: string, data: object) {
const state: StateModel = reactive({
isLoading: true,
isError: false,
errorMessage: '',
data: null
});
const fetchData = async () => {
try {
const response = await axios({
method: 'GET',
url: url, // '/test_data/campaign.json'
data: data
});
state.data = response.data;
} catch (e) {
state.isError = true;
state.errorMessage = e.message;
} finally {
state.isLoading = false;
}
};
return {
...toRefs(state),
fetchData
};
}
我使用状态的组件和我得到 TS 编译错误的位置:
setup() {
const state: StateModel = reactive({
data: null,
isLoading: true
});
const { data, isLoading, fetchData } = useAxios(
'/test_data/campaign.json',
{}
);
const getCampaignData = async () => {
await fetchData();
state.data = data as CampaignModel;
state.isLoading = isLoading; // ERROR HERE: Type 'Ref<boolean>' is not assignable to type 'boolean'
};
onMounted(() => {
getCampaignData();
});
return {
...toRefs(state)
};
}
为什么 TS 编译器会抱怨?我已经在 Hook 中定义了它是一个布尔值?
【问题讨论】:
标签: typescript vue.js vuejs3 vue-composition-api