【问题标题】:Vue 3 - Type 'Ref<boolean>' is not assignable to type 'boolean'Vue 3 - 类型 'Ref<boolean>' 不可分配给类型 'boolean'
【发布时间】: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


    【解决方案1】:

    您应该可以访问.value

     state.isLoading = isLoading.value;
    

    因为toRefs 返回一个ref

    【讨论】:

    • 太棒了,非常感谢...但是如果我对数据做同样的事情,我的模板中的 TS 绑定似乎会松动? state.data = data.value 作为 CampaignModel;也许是另一个问题,但是,我不太明白为什么? :) 有什么想法吗?
    • 你的意思是模板部分里面的类型推断?
    • 这个答案教会了我一些关于 Vue3 的事情,我不知道我错过了。即 ref() const 变量以及如何在 Javascript 端与它们交互。
    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    • 2019-01-04
    • 2023-01-22
    • 2020-08-29
    • 2023-01-18
    相关资源
    最近更新 更多