2017-07-20 6 views
2

私はそれがマウントされているときにトリガーするのを見たいと思っている以下のvueコンポーネントを持っています。それ、どうやったら出来るの?Vueトリガー・ウォッチ・オン・マウント

Vue.component('check-mark', { 
    name: 'check-mark', 
    template: ` 
    <input :value="value"> 
    `, 
    props: { 
     value: { 
      type: String, 
      required: true, 
     }, 
    }, 
    mounted: async function() { 
     //trigger this.value watch() here 
    }, 
    watch: { 
     value: function (value) { 
      if (value == 'Y') { 
       this.class = 'checked'; 
      } else { 
       this.class = 'unchecked'; 
      } 
     }, 
    }, 
}); 
+0

https://stackoverflow.com/questions/45354027/vue-js-how-to-fire-a-watcher-function-when-a-component-initializes –

答えて

3

この場合、あなたはより良いサービスを提供できると思います。

computed:{ 
    class(){ 
    return this.value === 'Y' ? 'checked' : 'unchecked' 
    } 
} 

実際にウォッチャーを使用する場合は、ウォッチャーで行ったコードをメソッドに抽象化し、マウントしてから呼び出すことができます。

Vue.component('check-mark', { 
    name: 'check-mark', 
    template: ` 
    <input :value="value"> 
    `, 
    props: { 
    value: { 
     type: String, 
     required: true, 
    }, 
    }, 
    data(){ 
    return { 
     class: null 
    } 
    }, 
    methods:{ 
    setClass(value){ 
     if (value == 'Y') { 
     this.class = 'checked'; 
     } else { 
     this.class = 'unchecked'; 
     } 
    } 
    }, 
    mounted: function() { 
    this.setClass(this.value) 
    }, 
    watch: { 
    value: function (value) { 
     this.setClass(value) 
    }, 
    }, 
}); 
+0

素晴らしいです!私はそれを計算された関数で処理させました。 – Raza

関連する問題