VUE监听器

196 阅读1分钟

监听器

  • 只要data中的值被改变了就会被触发
  • value属性需要和data中的属性相对应
  • 第一个参数newV表示最新的值 第二个参数oldV表示之前的值
value:function(newV,oldV){
console.log('value的值被改变了',a,b)
                }
  引用数据类型使用简写的方式无效 怎么办?改用对象的方式 加deep:true深度监听
      handler方法名是固定的不可以被篡改
      immediate:true 会立即执行监听器里面的handler方法
            watch:{
                // obj:{
                //     deep:true,
                //     handler:function(newV,oldV){
                //         console.log(newV,oldV)
                //         console.log('值被改了')
                //     },
                //     immediate:true
                // },
                'obj.value':function(){
                    console.log('简单粗暴的方式监听对象里面的值')
                },
            },
            methods: {
                change(){
                    this.obj.value++;
                }
            },
        })

计算属性

            /* 挂载点 */
            el: "#app",
            /* 数据 */
            data: {
                msg:'hello',
                price:1000.00000001,
                value:99
            },
            /* 计算属性 */
            /* 计算属性具有缓存的功能 */
            /* 当data里面的数据值被改变的时候 计算属性缓存的内容才会被刷新 */
            computed:{
                newMsg:function(){
                    /* this 指的就是Vue实例化对象 */
                    console.log(this)
                    /* 一定要return */
                    return this.msg.split('').reverse().join('')
                },
                priceV:function(){
                    /* toFixed会把数字转成字符串 参数是用来保留几位小数 并四舍五入 */
                    return '¥'+this.price.toFixed(2)
                },
                /* 把毫秒数1646874284591 转成 年月日 */
                dateV:function(){
                    let oDate = new Date(1646874284591);
                    return oDate.getFullYear()+'年'+(oDate.getMonth()+1)+'月'+oDate.getDate()+'日'
                },
                ceshi:function(){
                    return this.value +'---'+ Math.random();
                }
            },
            watch:{
                /* 如果监听的是计算属性 计算属性里面的data属性里面的值例如value 
                发生了改变,才会触发监听器 */
                ceshi:function(){
                    console.log(11111)
                }
            },
            /* 定义方法的地方 */
            methods: {
                getCeshi:function(){
                    console.log('方法getCeshi:',this.value +'---'+ Math.random())
                },
                getC:function(){
                    console.log('获取计算属性ceshi的值',this.ceshi)
                },
                changeD:function(){
                    this.value++
                },
                getDate:function(){
                    let oDate = new Date(1646874284591);
                    return oDate.getFullYear()+'年'+(oDate.getMonth()+1)+'月'+oDate.getDate()+'日'
                }
            },
        })