Vue學習之路(五)----Computed計算屬性與watch監聽

1.computed計算屬性常用於當value值變化時重新對值進行計算。舉個簡單的例子(當輸入框中的value值變化時,輸出結果爲無數字的字符串):

//html
<input type="text" v-model="value"/>{{valueWithoutNum}}
//data中
data () {
value: ''
}
//computed屬性中
computed: {
  vauleWithoutNum: function (){
    return this.value.replace('/\d/g','');//將輸入的數字變爲空
  }
}

結果圖

2.watch常用於監聽一個數據的變化,有時候,當數據變化時我們需要不斷的去執行一個函數,這個時候就需要用到watch了

//html
  <input type="text" v-model="value"/>
//data
  data () {
    value: ''
  }
//methods
  methods: {
    getNum () {
      console.log('獲取到了數據');
    }
  }
//watch
  watch: {
   value: funciton(newVal, oldVal){//newVal當前的值,old變化之前的值
     this.getNum();
   }
  }

結果圖
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章