【问题标题】:Importing a function in Vue 3 setup在 Vue 3 设置中导入函数
【发布时间】:2021-05-15 17:06:20
【问题描述】:

目前,我试图在我的 Vue 组件中调用一个节流/去抖动函数,但每次调用它时都会调用 Uncaught TypeError: functionTD is not a function si throw 这里是我的代码。

useThrottleDebounce.ts

import { debounce, throttle } from "lodash";
import { ref, watch } from "vue";

export const useThrottleDebounce = (tTime = 2000, dTime = 1000) => {
  const tRef = ref<any>(null);
  const tFunc = ref<any>(null);
  const tDHook = ref<any>(null);

  const debounceThrottle = debounce(() => {
    if (tRef.value) {
      tRef.value.cancel();
    }
    tRef.value = throttle(tFunc.value, tTime)();
  }, dTime);

  const throttleDebounceCreator = () => {
    return (func: any) => {
      tFunc.value = func;
      debounceThrottle();
    };
  };

  watch(() => tDHook.value, () => {
    tDHook.value = throttleDebounceCreator();
  });

  return tDHook;
};

export default useThrottleDebounce;

这是在我的组件中的 setup 中调用它的时候

setup(){
   // some code
   const functionTD = useThrottleDebounce(2000, 500);
   const inc = () => {      
      functionTD (() => {     
        count.value++; // here throw error
      });
    };
}

【问题讨论】:

  • const function = useThrottleDebounce(2000, 500); 是非法的 JavaScript。您不能在 JavaScript 中为任何保留字命名常量,function 就是其中之一。如果您需要帮助,请提供 runnable minimal reproducible example,包括实施和您想要实现的目标。
  • 我只是更新代码函数名
  • 这还不够。您没有展示如何使用它,也没有描述应该发生的事情与当前发生的事情。如果我运行上面的代码,我不会收到您描述的错误。你是如何使用你的函数的?
  • @tao 该函数正在使用,如最后一个代码 sn-p 所示

标签: javascript typescript vue.js vue-component vuejs3


【解决方案1】:

问题是useThrottleDebounce 不返回函数,因此functionTD 不是函数:

export const useThrottleDebounce = (tTime = 2000, dTime = 1000) => {
  // Maybe you want some private variables / functions here
  return () => {
    // This will be `functionTD` in `setup`
  }
}

【讨论】:

    猜你喜欢
    • 2022-08-20
    • 1970-01-01
    • 2022-01-05
    • 2022-10-23
    • 2022-01-09
    • 1970-01-01
    • 2021-11-23
    • 2021-03-13
    相关资源
    最近更新 更多