1. 程式人生 > >watch , computed和methods之間的區別

watch , computed和methods之間的區別

watch(偵聽器)

  • watch為物件形式,鍵是需要觀察的表示式,值是對應的回撥函式,主要用來監聽某些特定資料的變化,從而進行某些具體的業務邏輯操作,可以看成是computed和methods的結合體

下面是官方例子:

<div id="watch-example">
  <p>
    問一個問題:
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/
[email protected]
/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script> <script> var watchExampleVM = new Vue({ el: '#watch-example', data: { question: '', answer: '在你問問題之前,我不能給你答案!' }, watch: { // 如果 `question` 發生改變,這個函式就會執行 question: function (newQuestion, oldQuestion) { this.answer = 'Waiting for you to stop typing...' this.debouncedGetAnswer() } }, created: function () { // `_.debounce` 是一個通過 Lodash 限制操作頻率的函式。 // 在這個例子中,我們希望限制訪問 yesno.wtf/api 的頻率 // AJAX 請求直到使用者輸入完畢才會發出。想要了解更多關於 // `_.debounce` 函式 (及其近親 `_.throttle`) 的知識, // 請參考:https://lodash.com/docs#debounce this.debouncedGetAnswer = _.debounce(this.getAnswer, 500) }, methods: { getAnswer: function () { if (this.question.indexOf('?') === -1) { this.answer = 'Questions usually contain a question mark. ;-)' return } this.answer = 'Thinking...' var vm = this axios.get('https://yesno.wtf/api') .then(function (response) { vm.answer = _.capitalize(response.data.answer) }) .catch(function (error) { vm.answer = 'Error! Could not reach the API. ' + error }) } } }) </script>

computed(計算屬性)

  • computed屬性的結果會被快取,除非依賴的響應式屬性變化才會重新計算。主要當做屬性來使用

官方例子

<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    // 計算屬性的 getter
    reversedMessage: function () {
      // `this` 指向 vm 例項
      return this.message.split('').reverse().join('')
    }
  }
})

methods(方法)

  • methods方法表示一個具體的操作,主要書寫業務邏輯

官方例子

var vm = new Vue({
  data: { a: 1 },
  methods: {
    plus: function () {
      this.a++
    }
  }
})
vm.plus()
vm.a // 2

作者:輕酌~淺醉