VUE中watch的详细使用教程(推荐!)
1、watch是什么?
watch:是vue中常用的侦听器(监听器),用来监听数据的变化
2、watch的使用方式如下
watch: {
这里写你在data中定义的变量名或别处方法名: {
handler(数据改变后新的值, 数据改变之前旧的值) {
这里写你拿到变化值后的逻辑
}
}
}
3、watch监听简单案例(监听一个)
<template>
<div>
<div>
<input type="text" v-model="something">
</div>
</div>
</template>
<script>
export default {
name: "AboutView",
components: {},
data() {
return {
something: ""
}
},
watch: {
//方法1
"something"(newVal, oldVal) {
console.log(`新值:${newVal}`);
console.log(`旧值:${oldVal}`);
console.log("hellow world");
}
//方法2
"something": {
handler(newVal, oldVal) {
console.log(`新的值: ${newVal}`);
console.log(`旧的值: ${oldVal}`);
console.log("hellow world");
}
}
}
}
</script>在输入框中输入1、4 效果图如下:

4、watch监听复杂单一案例(例:监听对象中的某一项)
<template>
<div>
<div>
<input type="text" v-model="obj.something">
</div>
</div>
</template>
<script>
export default {
name: "AboutView",
components: {},
data() {
return {
obj: {
something: ""
}
}
},
watch: {
"obj.something": {
handler(newVal, oldVal) {
console.log(`新的值: ${newVal}`);
console.log(`旧的值: ${oldVal}`);
console.log("hellow world");
}
}
}
}
</script>在输入框中输入4、5 效果图如下:

5、watch中immediate的用法和作用
1、作用:immediate页面进来就会立即执行,值需要设为true
2、用法如下方代码所示:
<template>
<div>
<div>
<input type="text" v-model="obj.something">
</div>
</div>
</template>
<script>
export default {
name: "AboutView",
components: {},
data() {
return {
obj: {
something: ""
}
}
},
watch: {
"obj.something": {
handler(newVal, oldVal) {
console.log(`新的值: ${newVal}`);
console.log(`旧的值: ${oldVal}`);
console.log("hellow world");
},
immediate:true
}
}
}
</script>进来页面后立即加载,效果图如下:

6、watch中deep 深度监听的用法和作用
1、作用:deep 用来监听data中的对象,值需要设为true
2、用法如下方代码所示:
<template>
<div>
<div>
<input type="text" v-model="obj.something">
</div>
</div>
</template>
<script>
export default {
name: "AboutView",
components: {},
data() {
return {
obj: {
something: ""
}
}
},
watch: {
"obj": {
handler(newVal, oldVal) {
console.log(`新的值: ${newVal}`);
console.log(`旧的值: ${oldVal}`);
console.log("hellow world");
},
deep:true
}
}
}
</script>注意:
1、console.log(`新的值: ${newVal}`); 这种打印出来的是对象的类型,如下图:

2、console.log(newVal);这种打印出来的是对象本身,如下图:

总结
到此这篇关于VUE中watch的详细使用教程的文章就介绍到这了,更多相关VUE watch使用教程内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Vue3+TS+Vant3+Pinia(H5端)配置教程详解
这篇文章主要介绍了Vue3+TS+Vant3+Pinia(H5端)配置教程详解,需要的朋友可以参考下2023-01-01
解决在Vue中使用axios POST请求变成OPTIONS的问题
这篇文章主要介绍了解决在Vue中使用axios POST请求变成OPTIONS的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-08-08
解决router.beforeEach()动态加载路由出现死循环问题
这篇文章主要介绍了解决router.beforeEach()动态加载路由出现死循环问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-10-10
Element UI中v-infinite-scroll无限滚动组件使用详解
在移动端数据的更新中许多方法孕育而生,无限滚轮也是解决的方案一种,Element-ui为vue开发了一个事件(v-infinite-scroll),下面这篇文章主要给大家介绍了关于Element UI中v-infinite-scroll无限滚动组件使用的相关资料,需要的朋友可以参考下2023-02-02


最新评论