vue中的watch属性


watch可以用来监听vue实例中data数据的变化,然后触发触发这个watch中的对应的function处理函数

eg:

 watch: {
        // 监听data中firstname数据的变化
        firstname(newVal, oldVal) {
          // console.log("监听到了firstname的变化")
          // this.fulltname = this.firstname + "----" + this.lastname
          // 函数还有两个可用的参数,newVal和oldVal(newVal表示),newVal表示最新的值。oldVal表示旧值
          // console.log(newVal + "---" + this.lastname)
           this.fulltname = newVal + "--" + this.lastname
        },
        lastname(newVal) {
          // console.log("监听到了firstname的变化")
          // this.fulltname = this.firstname + "----" + this.lastname
          // 函数还有两个可用的参数,newVal和oldVal(newVal表示)
          // console.log(newVal + "---" + this.lastname)
          this.fulltname = this.firstname + "---" + newVal
        }
      },
watch还可以用来监听,一些费dom元素的操作。例如:路由的更换
  eg:可以直接使用watch来监听$route.path
  
   watch: {
        // watch可以监听一些非dom操作
        '$route.path'(newVal, oldVal) {
          // console.log(newVal + "-----------" + oldVal)
          if (newVal == "/logn") {
            console.log("切换到了登陆组件")
          }
          else if (newVal == '/resgist') {
            console.log("切换到了注册组件")
          }
        }
      },
  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM