当前位置: 首页 > news >正文

vue中事件监听watch

vue中的watch实际上是用来监听vue实例中的数据变化。

监听String

<template>
    <div @click="stringClick">{{msg}}</div>
</template>
<script>
export default {
    name: "jianting",
    data() {
        return {
            msg: "1223"
        };
    },
    watch: {
        msg: function(newVal, oldVal) {
            console.log("newVal:", newVal,  "oldVal:", oldVal) // 新值,旧值
        }
    },
    methods: {
        stringClick() {
            this.msg = Math.random() * 100;
        }
    }
};
</script>

监听对象

 <template>
    <div @click="click">
        <div>
        	姓名:{{obj.name}},
        	年龄:{{obj.age}},
        	他的儿女有:
        </div>
        <div 
        	v-for="(item, index) in obj.children" 
        	:key="index">
        	姓名:{{item.name}},
        	年龄:{{item.age}}
        </div>
    </div>
</template>

<script>
export default {
    name: "jianting",
    data() {
        return {
            obj: {
                name: "Tony",
                age: 50,
                children: [
                    {
                        name: "小明",
                        age: 12
                    },
                    {
                        name: "小花",
                        age: 5
                    }
                ]
            }
        };
    },
    watch: {
        obj: {
            handler: function(newVal, oldVal) {
                console.log("newVal:", newVal);
                console.log("oldVal:", oldVal);
            },
            deep: true, // 深度监听
            immediate: true // 立即执行
        },
        
        // 监听对象中的某个值
        "obj.name": function(newVal, oldVal) {
            console.log("newVal obj.name:", newVal);
            console.log("oldVal obj.name:", oldVal);
        }
    },
    methods: {
        click() {
            this.obj.name = "未知";
        }
    }
};
</script>

watch监听对象的时候,需要加deep:true,只有这样才能深入底层去实时监听,没有加的话,对象是监听不到变化的,添加immediate时会在侦听开始之后被立即调用

监听路由

通过watch监听,当路由发生变化时执行

  方法一监听以及路由
  监听一级路由:路由组件的渲染区域为router-view,
  	作为顶层出口,它将匹配到的路由组件渲染在该区域中,
  	路由组件渲染默认的方式是销毁 - 创建,
  	因此$watch是监听不到一级路由的变化的。
  	所以,要想使用$router监听一级路由,需要让组件成为复用组件,
  	也就是使用keep-alive包裹router-view。
  	
	<keep-alive>
	     <router-view />
	</keep-alive>
	
  watch: {
    $route: {
        handler: function(to, from) {
            console.log(to,'新',from, '旧');
             if(from && (from.name === 'adoptSelect')){
                this.active = 2
            }
        },
        // 深度观察监听
        deep: true,
        immediate: true
    }
}
方法二 监听子路由:
需要在有子路由的情况下,才能在当前组件监听到子组件的路由变化,直接使用下面的方式即可。
watch:{
	$route(to, from){
		console.log('去哪里',to,  '从哪里来',from)
		console.log(to.path)
	}
}
或者
 watch: {
  '$route.path': function (newVal, oldVal) {
   if (newVal === '/login') {
    console.log('欢迎进入登录页面');
   }
   if (newVal === '/register') {
    console.log('欢迎进入注册页面');
   }
  }
 }
方法三
watch: {
   '$route' : 'getPath' // 获取路径
},
methods: {
   getPath(){
     console.log( this .$route.path);
   }
}

key-用来阻止“复用”的

Vue 为我们提供了一种方式来声明“这两个元素是完全独立的——不要复用它们”。只需添加一个具有唯一值的 key 属性即可(Vue文档原话)

<router-view :key= "key" ></router-view> 
computed: { //计算属性
   key() {
     return  this .$route.name !== undefined 
     ?
     this .$route.name + new  Date() 
     :
     this .$route + new  Date()
   }
}
使用computed属性和Date()可以保证每一次的key都是不同的,
这样就可以如愿刷新数据了。

全局监听路由

(通过vue-router的钩子函数
beforeRouteEnter
/beforeRouteUpdate
/beforeRouteLeave)

一般会在router里面加跳转验证才会用到这个方法

方法一 监听路由导航守卫
watch:{
   $route(to,from){
     if (to.path ==  '/'  || to.path ==  '/Prisoner'  || to.path ==  '/Goods'  || to.path ==  '/Time'  || to.path ==  '/Mine' ){
       /**
        * $store来自Store对象
        * dispatch 向 actions 发起请求
        */
       this .$store.dispatch( 'showTabBar' );
     } else {
       this .$store.dispatch( 'hideTabBar' );
     }
   }
 },
 
 beforeRouteEnter (to, from, next) {
   // 在渲染该组件的对应路由被 confirm 前调用
   // 不!能!获取组件实例 `this`
   // 因为当钩子执行前,组件实例还没被创建
    if(from.name !== 'adoptDetail'){
          next({
              path:'/adopt'
          })
      }else{
          next()
      }
 },
 beforeRouteUpdate (to, from, next) {
   // 在当前路由改变,但是该组件被复用时调用
   // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
   // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
   // 可以访问组件实例 `this`
 },
 beforeRouteLeave (to, from, next) {
   // 导航离开该组件的对应路由时调用
   // 可以访问组件实例 `this`
 },
 
 方法二:
在app.vue的create中加入下面代码,然后进行判断
this.$router.beforeEach((to ,from,next) =>{
   console.log(to);
   next(); 
})
等等方法

相关文章:

  • Atitit.gui api自动化调用技术原理与实践
  • 数组中 includes()方法 : 包含
  • css清除浮动的意义
  • MySql——查看数据库性能基本参数
  • IDE有毒
  • 遍历数组,将数组中key值相同的对象合并
  • RAID磁盘阵列详细说明
  • linux下安装php的imagick扩展模块(附php升级脚本)
  • 正则校验非中文 加长度校验
  • Day8-php 文件的操作
  • toFixed() 踩坑----四舍六入 银行家算法
  • 基于.net开发chrome核心浏览器
  • juery 选择器 选择多个元素
  • Object.keys() 判断每一行的值是否相等
  • IBM公布Kitura 1.0和Bluemix Runtime for Swift 3
  • [译]如何构建服务器端web组件,为何要构建?
  • Computed property XXX was assigned to but it has no setter
  • Cookie 在前端中的实践
  • Linux各目录及每个目录的详细介绍
  • Markdown 语法简单说明
  • mysql外键的使用
  • Otto开发初探——微服务依赖管理新利器
  • React Transition Group -- Transition 组件
  • scala基础语法(二)
  • Twitter赢在开放,三年创造奇迹
  • XML已死 ?
  • 反思总结然后整装待发
  • 老板让我十分钟上手nx-admin
  • 那些年我们用过的显示性能指标
  • 爬虫模拟登陆 SegmentFault
  • 前嗅ForeSpider采集配置界面介绍
  • 小李飞刀:SQL题目刷起来!
  • 一文看透浏览器架构
  • 基于django的视频点播网站开发-step3-注册登录功能 ...
  • ​​快速排序(四)——挖坑法,前后指针法与非递归
  • (12)目标检测_SSD基于pytorch搭建代码
  • (2020)Java后端开发----(面试题和笔试题)
  • (HAL)STM32F103C6T8——软件模拟I2C驱动0.96寸OLED屏幕
  • (JS基础)String 类型
  • (附源码)计算机毕业设计ssm基于Internet快递柜管理系统
  • (理论篇)httpmoudle和httphandler一览
  • (论文阅读笔记)Network planning with deep reinforcement learning
  • (三) prometheus + grafana + alertmanager 配置Redis监控
  • (三分钟)速览传统边缘检测算子
  • (顺序)容器的好伴侣 --- 容器适配器
  • (四)图像的%2线性拉伸
  • (转)Linux整合apache和tomcat构建Web服务器
  • **登录+JWT+异常处理+拦截器+ThreadLocal-开发思想与代码实现**
  • . NET自动找可写目录
  • .NET Core WebAPI中使用swagger版本控制,添加注释
  • .NET delegate 委托 、 Event 事件,接口回调
  • .net 调用php,php 调用.net com组件 --
  • .NET 设计模式—适配器模式(Adapter Pattern)
  • @property括号内属性讲解
  • [2010-8-30]