watch的用法
阿新 • • 發佈:2019-01-14
turn oda 頻率 tle -- rip ann -c resp
1 <div id="watch-example"> 2 <p> 3 Ask a yes/no question: 4 <input v-model="question"> 5 </p> 6 <p>{{ answer }}</p> 7 </div> 8 <!-- 因為 AJAX 庫和通用工具的生態已經相當豐富,Vue 核心代碼沒有重復 --> 9 <!-- 提供這些功能以保持精簡。這也可以讓你自由選擇自己更熟悉的工具。 --> 10 <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script> 11<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script> 12 <script> 13 var watchExampleVM = new Vue({ 14 el: ‘#watch-example‘, 15 data: { 16 question: ‘‘, 17 answer: ‘I cannot give you an answer until you ask a question!‘ 18 }, 19 watch: { 20 //如果 `question` 發生改變,這個函數就會運行 21 question: function (newQuestion, oldQuestion) { 22 this.answer = ‘Waiting for you to stop typing...‘ 23 this.debouncedGetAnswer() 24 } 25 }, 26 created: function () { 27 // `_.debounce` 是一個通過 Lodash 限制操作頻率的函數。 28 // 在這個例子中,我們希望限制訪問 yesno.wtf/api 的頻率29 // AJAX 請求直到用戶輸入完畢才會發出。想要了解更多關於 30 // `_.debounce` 函數 (及其近親 `_.throttle`) 的知識, 31 // 請參考:https://lodash.com/docs#debounce 32 this.debouncedGetAnswer = _.debounce(this.getAnswer, 500) 33 }, 34 methods: { 35 getAnswer: function () { 36 if (this.question.indexOf(‘?‘) === -1) { 37 this.answer = ‘Questions usually contain a question mark. ;-)‘ 38 return 39 } 40 this.answer = ‘Thinking...‘ 41 var vm = this 42 axios.get(‘https://yesno.wtf/api‘) 43 .then(function (response) { 44 vm.answer = _.capitalize(response.data.answer) 45 }) 46 .catch(function (error) { 47 vm.answer = ‘Error! Could not reach the API. ‘ + error 48 }) 49 } 50 } 51 }) 52 </script>
PS:1.如果你的v-model為form.name,直接把question改為"form.name"就好了。
2.上面監聽的如果是數組或者是對象的時候console.log(newQuestion==oldQuestion)為true,因為這兩個形參指向同一個對象
watch的用法