51. Vue名稱案例-使用watch監聽數據變化

需求

上一章節,我才用了監聽keyup事件的方式,實現了一個名稱拼接的案例。那麼其中Vue框架提供一個watch組件,可以用來監聽數據的變化,然後再執行相關的業務方法。

那麼,本篇章則可以使用watch來實現。下面先來看看官網的基本功能說明。

偵聽器watch官網說明

雖然計算屬性在大多數情況下更合適,但有時也需要一個自定義的偵聽器。這就是爲什麼 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 請求直到用戶輸入完畢纔會發出。想要了解更多關於
    // `_.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>

結果:

Ask a yes/no question:

I cannot give you an answer until you ask a question!

在這個示例中,使用 watch 選項允許我們執行異步操作 (訪問一個 API),限制我們執行該操作的頻率,並在我們得到最終結果前,設置中間狀態。這些都是計算屬性無法做到的。

除了 watch 選項之外,您還可以使用命令式的 vm.$watch API

可以從上面的例子中看到,其實watch 簡單來說,上面的例子就是監聽一個v-model的參數,當監聽的參數發現變化,則執行編寫的函數方法。

下面我們在名稱拼接案例中運用一下。

示例

1.使用watch編寫名稱拼接案例代碼

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <!--  1.導入vue.js庫  -->
        <script src="lib/vue.js"></script>
    </head>
    <body>

        <div id="app">

            <!-- form>(label+input#input$+br)*3 -->
            <form action="">
                <label for="input1">姓氏:</label>
                <input type="text" id="input1" v-model="firstname" autocomplete="off">
                <br>
                <label for="input2">名稱:</label>
                <input type="text" id="input2" v-model="lastname" autocomplete="off">
                <br>
                <label for="input3">姓名:</label>
                <input type="text" id="input3" v-model="fullname">
                <br>
            </form>

        </div>

        <script>
            // 2. 創建一個Vue的實例
            var vm = new Vue({
                el: '#app',
                data: {
                    firstname: "",
                    lastname: "",
                    fullname: "",
                },
                methods: {},
                watch: { // 使用這個 屬性,可以監視 data 中指定數據的變化,然後觸發這個 watch 中對應的 function 處理函數
                    'firstname': function(newVal, oldVal) {
                        // watch對應的函數方法第一個參數newVal則是新值,oldVal則是變化之前的值。

                        console.log('監視到了 firstname 的變化');
                        console.log(newVal + ' --- ' + oldVal);
                        this.fullname = newVal + this.lastname

                    },
                    'lastname': function(newVal) {
                        console.log(newVal);
                        this.fullname = this.firstname + newVal
                    }
                }

            });
        </script>

    </body>
</html>

2.打開瀏覽器查看效果

可以從效果來看,使用watch可以實現這種數據變化,執行相關業務的方法。

更多精彩原創Devops文章,快來關注我的公衆號:【Devops社羣】 吧:

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