2. Vue

2023-05-22  本文已影响0人  努力生活的西鱼
16. 键盘事件
  1. Vue中常用的按键别名
<input type="text" placeholder="按下回车提示输入" @keyup.enter="showInfo">
  1. Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名)
<input type="text" placeholder="按下按键,提示信息" @keyup.caps-lock="showInfo">
  1. 系统修饰键(用法特殊): ctrl、alt、shift、win
<input type="text" placeholder="按下按键,提示信息" @keydown.ctrl="showInfo">
  1. 也可以使用keyCode去指定具体的按键(不推荐)
<input type="text" placeholder="按下按键,提示信息" @keyup.13="showInfo">
  1. Vue.config.keyCodes.自定义键名 = 键码,可以去定制按键别名
// 定义一个别名按键
Vue.config.keyCodes.huiche = 13

<input type="text" placeholder="按下按键,提示信息" @keyup.huiche="showInfo">
  1. 同时按下多个按键
<input type="text" placeholder="按下按键,提示信息" @keyup.ctrl.y="showInfo">
17. 计算属性
computed: {
    // 完整的写法
    fullName: {
        // get有什么作用? 当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
        // get什么时候调用,1.初次读取fullName时 2.所依赖的fullName发生变化时
        get() {
            return this.firstName + '-' + this.lastName
        },
        // set什么时候调用? 当fullName被修改时
        set(value) {
            const arr = value.split('-')
            this.firstName = arr[0]
            this.lastName = arr[1]
        }
    },
    // 简写(没有set的时候)
    fullName2: function () {
        return this.firstName + this.lastName
    }
}
22. 监视属性 watch

监视属性watch:

watch: {
    isHot: {
        // 初始化时,让handler调用一下
        immediate: true, 

        // handler什么时候调用? 当isHot发生改变时
        handler(newValue, oldValue) {
            console.log('isHot被修改了',newValue, oldValue)
        }
    }
}
vm.$watch('isHot',{
    immediate: true,
    handler(newValue, oldValue) {
        console.log('isHot被修改了',newValue, oldValue)
    }
})
23. 深度监视

深度监视:

data: {
    numbers: {
        a: 1,
        b: 1
    }
}

watch: {
    // 监视多级结构中某个属性的变化
    'numbers.a': {
        handler() {
            console.log('a改变了')
        }
    },
    numbers: {
        // 深度监视
        deep: true,
        handler() {
            console.log('numbers发生了改变')
        }
    }
}

备注:

上一篇 下一篇

猜你喜欢

热点阅读