javascript Vue3我如何使这个钩子React

wi3ka0sx  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(207)

我有一个钩子,看起来像这样(简化这个例子):

export const useOpeningHours = (
  flight: Ref<FlightOption | null>,
  identifier: string,
  isEnabled?: boolean
) => {
  if (!flight.value) {
    return {
      show: false,
      gate: "",
    };
  }
}

const flight = ref<FlightOption | null>(null);

const { show: showOpeningHours } = useOpeningHours(
  flight,
  props.identifier,
  true
);

因为我使用Ref<FlightOption | null>,所以我希望当flight改变时钩子会被“刷新”。然而,这并没有发生。我如何确保这个例子中的钩子是React性的呢?

dgsult0t

dgsult0t1#

既然你说这是简化的,我就把它当作一个复杂的事情来处理,你有三种方法

使用ComputedRef

更多信息:https://vuejs.org/guide/essentials/computed.html#basic-example

export const useOpeningHours = (
  flight: Ref<FlightOption | null>,
  identifier: string,
  isEnabled?: boolean
) => {
    return {
      show: computed(() => {
        if (flight.value) return false
        return true
      }),
      gate: computed(() => {...}),
    }
}

这将返回showgate是一个ComputerRef,它与show.value相同
如果使用@vueuse/core,则有一种更简单的方法

export const useOpeningHours = (
  flight: Ref<FlightOption | null>,
  identifier: string,
  isEnabled?: boolean
) => {
  return toReactive(computed(() => {
    if (!flight.value) {
      return {
        show: false,
        gate: "",
      };
    }

    return {
      show: ...,
      gate: ...
    } 
  }))
}

const flight = ref<FlightOption | null>(null);

const { show: showOpeningHours } = toRefs(useOpeningHours(
  flight,
  props.identifier,
  true
));

使用React性

export const useOpeningHours = (
  flight: Ref<FlightOption | null>,
  identifier: string,
  isEnabled?: boolean
) => {
  const result = reactive({ <default value> })

  watchEffect(() => { // or watch, watchPostEffect, watchSyncEffect
    if (!flight.value) {
      result.show = false
      result.gate = ""
    }
    ...
  })

  return result
}

const flight = ref<FlightOption | null>(null);

const { show: showOpeningHours } = toRefs(useOpeningHours(
  flight,
  props.identifier,
  true
));

使用Ref

export const useOpeningHours = (
  flight: Ref<FlightOption | null>,
  identifier: string,
  isEnabled?: boolean
) => {
  const show = ref(false)
  const gate = ref("")

  watch(flight, flight => { // or watchEffect
    if (!flight) {
      show.value = false
      gate.value = ""
    }

    ...
  }, { immediate: true })

  return { show, gate }
}
4dbbbstv

4dbbbstv2#

尝试按如下方式使用计算属性:

export const useOpeningHours = (flight: Ref<FlightOption | null>, identifier: string, isEnabled?: boolean) => {
  const details = computed(() => {
    if (!flight.value) {
      return {
        show: false,
        gate: "",
      };
    } else {
      return {
        show: true,
        gate: "GATE 1",
      };
    }
  });

    return {
        details
    };
};

像这样使用它:

const { details } = toRefs(useOpeningHours(
  flight,
  props.identifier,
  true
));

//then use `details.value.show` or `details.value.gate`

相关问题