双向数据绑定与自定义指令扩展

200 阅读1分钟

一、双向绑定

1、数据劫持原理

 <button id="btn">点击切换text的值</button>
let obj = {}
var num = 10
// 对象方法 动态添加属性 define -- 定义  Property -- 属性
// Object.defineProperty(对象名,定义属性,配置项 }
Object.defineProperty(obj, 'text', {
    get() {
        // 返回text的值
        return num
    },
    set(val) {
        num = val
    }
})
btn.onclick = function () {
    // 修稿obj.text 时会自动触发 setter 并且获取一个新的值
    obj.text = 50
    console.log(obj.text);
}
console.log(obj.text);

2、对象属性的配置

// let obj={
//     msg:'hello'
// }
// console.log(obj.msg);
let obj = {}
Object.defineProperty(obj, 'msg', {
    value: '你好世界',       // 使用value 给key添加值
    writable: true,         // 设置key是否可修改
    configurable: true,     //实在key是否可删除
    enumerable: true,       //设置key 是否可枚举(能否被罗列/展现)出来
})
console.log(obj.msg);
// 重新赋值
obj.msg = 'hello'
console.log(obj.msg);
// 查看obj所以key  ---  Object.keys()方法 查看某个对象所以key值
console.log(Object.keys(obj));
// 删除属性
delete obj.msg
console.log(obj.msg);

二、自定义指令的使用

1、全局自定义指令

.box {width: 100px;height: 100px;background: aqua;}
<div id="app">
    <button @click="flag=!flag">显示/隐藏</button>
    <div class="box" v-myshow="flag"></div>
</div>
 // 全局
 Vue.directive('myshow', {
     // 添加 - 第一次添加到父节点时
     inserted(e, type) {
         e.style.display = type.value ? 'block' : 'none'
     },
     // 更新
     update(e, type) {
         e.style.display = type.value ? 'block' : 'none'
     }
 })
 new Vue({
     el: "#app",
     data: {
         flag: true
     },
 })

2、局部自定义指令

.box { width: 100px; height: 100px;background: aqua; }
<div id="app">
    <button @click="flag=!flag">显示/隐藏</button>
    <div class="box" v-myshow="flag"></div>
</div>
new Vue({
    el: "#app",
    data: {
        flag: true
    },
    // 局部
    // 自定义指令
    directives: {
        myshow: {
            // 添加 - 第一次添加到父节点时
            inserted(e, binding) {
                e.style.display = binding.value ? 'block' : 'none'
            },
            update(e, binding) {
                e.style.display = binding.value ? 'block' : 'none'
            }
        }
    }
})

3、自动聚焦案例

input{
            width: 1000px;
            height: 500px;
            font-size: 350px;
            padding: 10px 250px;
           border: none;
            border-radius: 500px;
        }
        input:focus{
            outline:2px  solid  red;
        }
<div id="app">
        <input type="text" v-focus>
    </div>
new Vue({
    el: "#app",
    data: {
    },
    directives: {
        focus: {
            inserted(e) {
                e.focus()
            },
        }
    }
})