如何正确分类vue的方法?

时间:2017-12-14 09:04:05

标签: vue.js

我试图在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>
&#13;
&#13;
&#13;

我尝试使用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 个答案:

答案 0 :(得分:1)

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>