作用:监视数据变化,执行一些业务逻辑或异步操作。
语法:
1.简单写法->简单类型数据,直接监视
const app = new Vue({
el: '#app',
data: {
words:''
},
watch:{
words(newValue,oldValue){
}
}
})
const app = new Vue({
el: '#app',
data: {
obj: {
words: ''
}
},
watch: {
'obj.words'(newValue) {
}
}
})
案例:翻译软件
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="app">
<textarea rows="10" cols="40" v-model="obj.words"></textarea>
<textarea rows="10" cols="40" v-model="result"></textarea>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
obj: {
words: ''
},
result: '',
timer: null
},
watch: {
'obj.words'(newValue) {
clearTimeout(this.timer)//防抖
this.timer = setTimeout(async () => {
const res = await axios({
url: 'https://applet-base-api-t.itheima.net/api/translate',
params: {
words: newValue
}
})
this.result = res.data.data
}, 300)
}
}
})
</script>
</body>
</html>
2.完整写法->添加额外配置项
1)deep:true对复杂类型深度监视
2)immediate:true初始化立刻执行一次handler方法
const app = new Vue({
el: '#app',
data: {
obj: {
words: '',
lang:''
}
},
watch: {
数据属性名:{
deep:true,//深度监视
immediate: true,//立即执行,一进入页面handler就立刻执行
handler(newValue){
}
}
}
})
案例:翻译软件Pro
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="app">
翻译成语言:<select v-model="obj.lang">
<option value="english">英语</option>
<option value="franch">法语</option>
<option value="italy">意大利</option>
</select>
<br><br>
<textarea rows="10" cols="40" v-model="obj.words"></textarea>
<textarea rows="10" cols="40" v-model="result"></textarea>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
obj: {
words: '',
lang: 'english'
},
result: '',
timer: null
},
watch: {
obj: {
deep: true,
immediate: true,
handler(newValue) {
clearTimeout(this.timer)//防抖
this.timer = setTimeout(async () => {
const res = await axios({
url: 'https://applet-base-api-t.itheima.net/api/translate',
params: newValue
})
this.result = res.data.data
}, 300)
}
}
}
})
</script>
</body>
</html>