2017-08-12 14 views
1

Vue.jsを初めて使用していて、すべての機能を練習しています。私はこのコードに基づいてインクリメントとデクリメントのための再利用可能な関数を書くことができるのだろうかと思っていました。ですから、私は2つの異なるボタンのインクリメント/デクリメント機能を使用したいと思います。 Here's jsfiddle demo!Vue.jsの再利用可能なインクリメント機能とデクリメント機能

new Vue ({ 
    el: "#pomodoro-clock", 
    data: { 
    breakLength: 5, 
    sessionLength: 25, 
    }, 
    methods: { 
    addBreak: function(inc){ 
     this.breakLength += inc; 
    }, 
    subtractBreak: function(dec){ 
     if(this.breakLength === 1) return; 
     this.breakLength -= dec; 
    }, 
    addSession: function(inc){ 
     this.sessionLength += inc; 
    }, 
    subtractSession: function(dec){ 
     if(this.sessionLength === 1) return; 
     this.sessionLength -= dec; 
    } 
    } 
}); 

答えて

1

ここでは、再利用可能なメソッドの例を示します。

methods: { 
    inc(property, amt){ 
    this[property] += amt 
    }, 
    dec(property, amt){ 
    if (this[property] === 1) return 
    this[property] -= amt 
    }, 
    ... 
} 

そして、あなたのテンプレートで:fiddleを更新しました

<span class="clock__btn--add" v-on:click="inc('breakLength', 1)">+</span> 
<span class="clock__break-length">{{breakLength}}</span> 
<span class="clock__btn--subtract" v-on:click="dec('breakLength', 1)">-</span> 

+0

ありがとうございました!私はそれを使用するつもりだ! –

+0

このコードは、コンポーネントのスコープ内でのみ再利用可能です。他のコンポーネントからはアクセスできません。受け入れられた答えではありません。 –

+0

@KamgaSimoJuniorもし彼が他のコンポーネントでそれらを再利用したいのであれば、これらはmixinやプラグインに必要に応じて簡単に移すことができます。 – Bert

0

新しいファイル名をfunctions.jsとして作成し、ファイル内のすべての関数を定義することができます。あなたは今、あなたの関数がthis.$functions

new Vue ({ 
    el: "#pomodoro-clock", 
    data: { 
    breakLength: 5, 
    sessionLength: 25, 
    }, 
    methods: { 
    addBreak: function(inc){ 
     this.breakLength = this.$functions.increment(this.breakLength, inc) 
    }, 
    subtractBreak: function(dec){ 
     if(this.breakLength === 1) return; 
     this.breakLength = this.$functions.decrement(this.breakLength, dec) 
    }, 
    addSession: function(inc){ 
     this.sessionLength = this.$functions.increment(this.sessionLength, inc) 
    }, 
    subtractSession: function(dec){ 
     if(this.sessionLength === 1) return; 
     this.sessionLength = this.$functions.decrement(this.sessionLength, dec) 
    } 
    } 
}); 

ORすることができます時間を節約するを使用してオブジェクトでき​​るコンポーネントでmain.js

import Functions from './functions.js' 
Vue.use(Functions) 

使用

であなたの関数をインポートすることができます

export default function (Vue) { 

    Vue.functions = { 

     // increment function 
     increment (data, inc) { 
      data += inc; 
      return data; 
     }, 

     // decrement function 
     decrement (data, dec) { 
      data -= dec; 
      return data; 
     } 

    } 

    Object.defineProperties(Vue.prototype, { 
     $functions: { 
      get:() => { 
       return Vue.functions 
      } 
     } 
    }) 
} 

buttonsに直接お使いください歌う$functions.functionName

<button @click="breakLength = $functions.increment(breakLength, inc)">Increment Value</button> 

関連する問題