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("切换到了注册组件")
          }
        }
      },
  
posted @ 2020-06-08 11:30  小小小~  阅读(1578)  评论(0编辑  收藏  举报