需求
上一章节,我才用了监听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>
<script src="https:///npm/axios@0.12.0/dist/axios.min.js">script>
<script src="https:///npm/lodash@4.13.1/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#debouncethis.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编写名称拼接案例代码
span style="line-height: 26px;">html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="lib/vue.js">script>
head>
<body>
<div id="app">
<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.打开浏览器查看效果
image-20200301185013048
image-20200301185033401
可以从效果来看,使用watch可以实现这种数据变化,执行相关业务的方法。