其他分享
首页 > 其他分享> > Vue侦听器(Vue07)

Vue侦听器(Vue07)

作者:互联网

侦听器

监测 vue 实例上的 数据变化 (监听data中的数据的)
功能:当这个数据变化时,可以监听到(有一个函数会自动运行)

// 创建实例 新增 watch属性
new Vue({
  data:{
    msg:'a',
    obj:{
      a:10,
      b:20
    }
  },
  watch:{
    // 侦听基础数据类型数据 直接写同名的方法即可
    msg(newVal, oldVal){ // newVal改变后的新值
      // 当msg改变这个方法会调用
    },
    // 侦听对象 
    // 直接侦听对象的某个属性
    'obj.a'(newVal, oldVal){

    },
    // 侦听对象 深度监听
    obj:{
      handler(newVal,oldVal){},
      deep: true
    }
  }
})

例子:
输入firstname和lastname,自动合成fullname
(使用监听器,监听firstname和lastname的变化)

<div id="app">
    firstname: <input type="text" v-model="firstname"><hr>
    lastname: <input type="text" v-model="lastname"><hr>
    fullname: {{fullname}}
 </div>
const vm = new Vue({
      el: '#app',
      data: {
        firstname: "",
        lastname: "",
        fullname: ""
      },
      methods: {
      },
      watch: {
        firstname(newVal){
          this.fullname = newVal + "." + this.lastname
        },
        lastname(newVal){
          this.fullname = this.firstname + "." + newVal
        }
      }
    })

侦听器

标签:Vue07,Vue,firstname,newVal,lastname,侦听器,fullname,侦听,监听
来源: https://blog.csdn.net/m0_37795535/article/details/109719935