Vue2学习之路 · 二 :事件、计算属性、监视属性

85 阅读5分钟

事件

事件的基本使用

1、使用v-on:xxx 或 @xxx 绑定事件,其中xxx是事件名,比如click

2、事件的回调需要配置子啊methods对象中,最终在vm上

3、methods中配置的函数们不要使用箭头函数,否则this就不是vm的

4、methods中配置的函数,都是被Vue所管理的函数,this的执行是vm或是组件实例对象

5、@click="demo" 和 @click="demo($event)"

效果一样,但是后者可以传递参数,其中$event是传递事件对象,其他参数用逗号分隔

事件修饰符

1、prevent:阻止默认事件

2、stop:阻止事件冒泡

3、once:事件只触发一次

4、capture:使用事件的捕获模式

5、self:只有event.target是当前操作的元素时,才会触发事件

6、passive:事件的默认行为立即执行,无需等待事件回调函数执行完毕

注意:修饰符可以连续写,例如下面代码,先阻止冒泡,再阻止默认行为

<div @click="showInfo">
   <a href="http://www.baidu.com" @click.stop.prevent="showInfo">点就完了</a>
</div>

键盘事件

1、Vue中常用的按键的别名

  • 回车 enter
  • 删除 delete(包括删除和退格键)
  • 退出 esc
  • 空格 space
  • 换行 tab(必须配合keydown使用)
  • 上 up
  • 下 down
  • 左 left
  • 右 right

2、Vue中未提供别名的按键,可以使用按键原始的key只去绑定,但注意要转为kebab-case(短横线命名)

3、系统修饰键(用法特殊):ctrl、alt、shift、meta(win键)

配合keyup使用:按下修饰键的同时,再按下其他键,然后释放其他键,事件才被触发

配合keydown使用:正常触发事件

<div id="root">
    <h2>欢迎来到{{name}}学习</h2>
    <input type="text" placeholder="按下回车提示输入" @keyup.enter="showInfo"/>
</div>
<script>
    //这是定义一个别名按键 
    Vue.config.keyCodes.huiche = 13;
    new Vue({
        el:'#root',
        data:{
            name:'稀土掘金'
        },
        methods:{
            showInfo(e){
                // console.log(e.key);
                console.log(event.target.value);
            }
        }
    });
</script>

注意:可以在系统修饰键后面加其它字母,让它必须在两个按键都按了才能触发事件

<div id="root">
    <h2>欢迎来到{{name}}学习</h2>
    <input type="text" placeholder="按下回车提示输入" @keyup.ctrl.a="showInfo"/>
</div>
<script>
    //这是定义一个别名按键 
    Vue.config.keyCodes.huiche = 13;
    new Vue({
        el:'#root',
        data:{
            name:'稀土掘金'
        },
        methods:{
            showInfo(e){
                // console.log(e.key);
                console.log(event.target.value);
            }
        }

    });
</script>

计算属性(computed)

要使用的属性其实是不存在的,要通过已有的属性计算得来,这个已有属性不能脱离Vue的管理,底层借助了Object.defineProperty方法提供的get和set

当有人读取当前计算属性时,get就会被调用,并且返回值就作为当前计算属性的值

get调用时间:初次读取计算属性时、所依赖的数据发生改变时

当前计算属性被修改时,就会调用set方法

与methods的实现相比,计算属性内部有缓存机制,效率更高,调试方便,还能复用

计算属性最终会出现在vm上,直接读取就能使用

如果计算属性要被修改,就必须用set函数去响应修改,且set中要引起计算时依赖的数据发生该改变

<div id="root">
    姓:<input type="text" v-model="firstname"><br>
    名:<input type="text" v-model="lastname"><br>
    姓名:<span>{{fullName}}</span>
</div>
<script>
    new Vue({
        el:'#root',
        data:{
            firstname:'赵',
            lastname:'云'
        },
        computed:{
            fullName:{
                get(){
                    return this.firstname + this.lastname
                },
                set(value){
                    console.log(value);
                }
            }
        }
    });
</script>

计算属性是可以简写的,但前提是计算属性不需要修改,没有set方法才能简写

<div id="root">
    姓:<input type="text" v-model="firstname"><br>
    名:<input type="text" v-model="lastname"><br>
    姓名:<span>{{fullName}}</span>
</div>
<script>
    new Vue({
        el:'#root',
        data:{
            firstname:'赵',
            lastname:'云'
        },
        computed:{
            fullName(){
                return this.firstname+this.lastname
            }
        }
    });
</script>

监视属性(watch)

当被监视的属性改变时,回调函数自动调用,进行操作,监视的属性必须存在,才能进行监视

第一种写法

new Vue时传入watch配置

<div id="root">
    <h2>今天天气:{{info}}</h2>
    <button @click="changeWeather">切换天气</button>
</div>
<script>
    const vm = new Vue({
        el:'#root',
        data:{
            isHot:true
        },
        computed:{
            info(){
                return this.isHot ? '炎热' : '凉爽';
            }
        },
        methods: {
            changeWeather(){
                this.isHot = !this.isHot;
            }
        },
        // 设置监视的两种方式
        // 方式一
        watch:{
            //要监视的属性
            isHot:{
            //当监视的属性发生改变时,就会调用handler方法
                handler(){
                    console.log("改了");
                }
            }
        }
    })
</script>

第二种写法

通过vm.$watch()监视

<div id="root">
    <h2>今天天气:{{info}}</h2>
    <button @click="changeWeather">切换天气</button>
</div>
<script>
    const vm = new Vue({
        el:'#root',
        data:{
            isHot:true
        },
        computed:{
            info(){
                return this.isHot ? '炎热' : '凉爽';
            }
        },
        methods: {
            changeWeather(){
                this.isHot = !this.isHot;
            }
        }
    })
    // 方式二,必须先有Vue实例才能使用
    vm.$watch('isHot',{
        handler(){
            console.log("改了");
        }
    });
</script>

深度监视

1、Vue中的watch默认不检测对象内部值的改变(一层)

2、配置deep:true 可以检测对象内部值的改变(多层)

3、Vue自身可以检测对象内部值的改变,但Vue提供的wathch默认不可以,使用watch是根据数据的具体结构,决定是否采用深度监视

<div id="root">
    <h2>今天天气:{{info}}</h2>
    <button @click="changeWeather">切换天气</button>
    <hr>
    <h3>a的值是:{{numbers.a}}</h3>
    <button @click="numbers.a++">点我让a+1</button>
    <hr>
    <h3>b的值是:{{numbers.b}}</h3>
    <button @click="numbers.b++">点我让b+1</button>
</div>
<script>
    const vm = new Vue({
        el:'#root',
        data:{
            isHot:true,
            numbers:{
                a:1,
                b:1
            }
        },
        computed:{
            info(){
                return this.isHot ? '炎热' : '凉爽';
            }
        },
        methods: {
            changeWeather(){
                this.isHot = !this.isHot;
            }
        },
        watch:{
            isHot:{
                handler(){
                    console.log("改了");
                }
            },

            // 监视多级结构中某个属性的变化,要加引号
            // 'numbers.a':{
            //     handler(){
            //         console.log('a变了');
            //     }
            // }

            // 监视多级结构中某个属性的变化
            numbers:{
                // 这是一条关键语句
                deep:true,

                handler(){
                    console.log('变了');
                }
            }

        }
    })
</script>

监视属性简写

<div id="root">
    <h2>今天天气:{{info}}</h2>
    <button @click="changeWeather">切换天气</button>
</div>
<script>
    const vm = new Vue({
        el:'#root',
        data:{
            isHot:true,
        },
        computed:{
            info(){
                return this.isHot ? '炎热' : '凉爽';
            }
        },
        methods: {
            changeWeather(){
                this.isHot = !this.isHot;
            }
        },
        watch:{
            // 方式一
            // 完整形式
            // isHot:{
            //     // 初始化的时候调用一下handler
            //     immediate:true,
            //     handler(){
            //         console.log("改了");
            //     }
            // }

            // 简写形式
            // 当所需要的监视只有handler,不需要其他配置属性时,就可以使用简写形式
            // 语法:要监视的属性名(){}
            // isHot(){
            //     console.log("改了");
            // }
        }
    })

    // 方式二的完成形式
    // vm.$watch('isHot', {
    //     handler(){
    //         console.log('真的改了@@@@@');
    //     }
    // })

    // 方式二的简写形式
    vm.$watch('isHot', function(){
        console.log('确定改了!!');
    })
</script>

computed和watch之间的区别

1、computed能完成的功能,watch都可以完成

2、watch能完成的功能,computer不一定能完成,比如watch可以进行异步操作,computed不能

3、被Vue所管理的函数,最好写成普通函数,这样this就会指向vm或是组件实例对象

不被Vue所管理的函数,如定时器的回调函数、ajax的回调函数等,最好写成箭头函数,这样this才会指向vm或是组件实例对象

<div id="root">
    姓:<input type="text" v-model="firstname"><br>
    名:<input type="text" v-model="lastname"><br>
    姓名:<span>{{fullName}}</span>
</div>
<script>
    new Vue({
        el:'#root',
        data:{
            firstname:'赵',
            lastname:'云',
            fullName:' '
        },
        // 使用计算属性
        // computed:{
        //     fullName(){
        //         return this.firstname+this.lastname
        //     }
        // }

        // 使用监视属性
        watch:{
            firstname(newValue){
                // 在watch监视属性中的定时器中的回调函数必须使用箭头函数
                setTimeout(()=>{
                    this.fullName = newValue+this.lastname; 
                },1000)
                // this.fullName = newValue+this.lastname;

            },
            lastname(newValue){
                    this.fullName = this.firstname+newValue
            }
        }
    });
</script>