Vue學習筆記之偵聽器--一個完整代碼瞬間讀懂vue

 參考官網   https://cn.vuejs.org/v2/guide/list.html

一個完整代碼瞬間讀懂vue 

偵聽器 Vue  watch 選項提供了一個更通用的方法,來響應數據的變化。當需要在數據變化時執行異步或開銷較大的操作時,這個方式是最有用的

<div id="watch-example">

  <p>

    Ask a yes/no question:

    <input v-model="question">

  </p>

  <p>{{ answer }}</p>

</div>

<!-- AJAX 庫和通用工具的生態已經相當豐富,Vue 核心代沒有重複 -->

<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: 'I cannot give you an answer until you ask a question!'

  },

  watch: {

    // 如果 `question` 發生改變,這個函數就會運行

    question: function (newQuestion, oldQuestion) {

      this.answer = 'Waiting for you to stop typing...'

      this.debouncedGetAnswer()

    }

  },

  created: function () {

    // `_.debounce` 是一個通 Lodash 限制操作率的函數。

    // 個例子中,我希望限制訪問 yesno.wtf/api

    // AJAX 請求直到用戶輸入完畢纔會發出。

    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>

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