【问题标题】:Vue lodash debounce method can work, but this typing is wrong, how can I solve it?vue lodash debounce方法可以工作,但是这个打错了,怎么解决?
【发布时间】:2021-04-14 02:29:06
【问题描述】:

请看这个最小的例子

<template>
  <div>
    <button @click="toggleShow">Toggle</button>

    <div v-if="show">Show</div>
  </div>
</template>

<script lang="ts">
import { extend } from "vue";
import { debounce } from "lodash";

export default extend({
  data() {
    return {
      show: false,
    };
  },
  methods: {
    toggleShow: debounce(async function () {
      this.show = !this.show; // TypeScript yells that `this` is any here!
    }, 1000),
  },
});
</script>

CodeSandbox Link

在异步功能块中,TypeScript 抱怨 thisany

但是,代码仍然有效!

我该如何解决这个问题?

【问题讨论】:

    标签: vue.js vuejs2 vue-component lodash


    【解决方案1】:

    我找到了方法

    <template>
      <div>
        <button @click="toggleShow">Toggle</button>
    
        <div v-if="show">Show</div>
      </div>
    </template>
    
    <script lang="ts">
    import { extend } from "vue";
    import { debounce } from "lodash";
    
    export default extend({
      data() {
        return {
          show: false,
        };
      },
      methods: {
        toggleShow() {
          this.show = !this.show
        }
      },
      computed() {
        debouncedToggleShow(): Function {
          return debounce(this.toggleShow, 1000)
        }
      }
    });
    </script>
    
    

    【讨论】:

      猜你喜欢
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 2015-05-15
      • 2022-06-15
      • 1970-01-01
      • 2023-01-24
      相关资源
      最近更新 更多