代码之家  ›  专栏  ›  技术社区  ›  Daniel YC Lin

如何正确分类vue的方法?

  •  0
  • Daniel YC Lin  · 技术社区  · 7 年前

    我正在尝试在vue上编写一个方法,原始代码在这里,它是可行的。

    new Vue({
      el: '#app',
      data: {
             buttonText : 'A'
      },
      methods: {
        clickA: _.throttle(function() {
          var date = new Date();
          var time = date.toLocaleTimeString();
          console.log('A clicked', time)
          this.buttonText = 'my button' + time; 
        }, 1000)
      }
    });
    <script src="https://unpkg.com/vue@2.5.10/dist/vue.min.js"></script>
    <script src="https://unpkg.com/lodash@4.17.4/lodash.min.js"></script>
    <div id="app">
      <button type="button" @click="clickA">{{buttonText}}</button>
    </div>

    我想用 vue-class-component 并将其分类如下,它已编译但单击无法工作。

    <script lang="ts">
    import Vue from 'vue'
    import { Component } from 'vue-property-decorator'
    import throttle from 'lodash/throttle'
    
    @Component
    export default class App extends Vue {
      clickA () {
        throttle(function () {
          var date = new Date();
          var time = date.toLocaleTimeString();
          console.log('A clicked', time)
          this.buttonText = 'my button' + time;
        }, 1000) // max one submit per second
      }
    }
    </script>
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Vamsi Krishna    7 年前

    throttle 返回函数。所以调用 throttle() 并将其分配给 clickA 这样地:

    <script lang="ts">
    import Vue from 'vue'
    import { Component } from 'vue-property-decorator'
    import throttle from 'lodash/throttle'
    
    @Component
    export default class App extends Vue {
      clickA = throttle(function () {
          var date = new Date();
          var time = date.toLocaleTimeString();
          console.log('A clicked', time)
        }, 1000) // max one submit per second
    }
    </script> 
    

    编辑:

    <button type="button" @click="clickA">{{buttonText}}</button>
    

    剧本

    <script lang="ts">
    import Vue from 'vue'
    import { Component } from 'vue-property-decorator'
    import throttle from 'lodash/throttle'
    
    @Component
    export default class App extends Vue {
        buttonText = 'my button';
    
      clickA = throttle( () => {
          var date = new Date();
          var time = date.toLocaleTimeString();
          console.log('A clicked', time)
           /// change button text
    
            this.buttonText = 'my button' + time;
    
    
        }, 1000) // max one submit per second
    }
    </script>