js模拟v-model指令

           v-model原理是通过使用v-model指令在元素的输入元素上创建双向数据绑定,它会根据控件类型自动选取正确的方法来更新元素。v-model 本质上不过是语法糖。它负责监听用户的输入事件以更新数据。 当input输入框值改变/复选框值改变时,text/checkbox值也会同时改变,它负责监听用户的输入事件以更新数据。

一、先写两个标签和对应的data数据。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text">
    <p></p>
</body>
<script>
    let data ={
        msg:'vue的双向数据绑定'
    }
</script>
</html>

二、通过获取对应的标签,先初始化他的值。

    
    const inpBT = document.querySelector('input');
    const pBT = document.querySelector('p')
    inpBT.value = data.msg
    pBT.innerHTML = data.msg

三、使用Object.defindProperty中的方法。

        Object.defindProperty中有三个参数。即obj:对象, prop:key, descriptor:属性和方法。

Object.defineProperty(data,'msg',{
        // configurable  表示可配置的,默认值为false
        // enumerable    表示可枚举的
        // value         表示属性对应的值,默认undefined
        // writable      能被赋值运算符更改成功 
        // 当获取该属性时,执行get函数,属性值就是get函数的返回值
        get:function(){
        },
        // set方法默认会将设置的值作为set函数的第一个参数传递进去
        set:function(newValue){
            // 通过这个方法讲data与标签进行复制更新
            inpBT.value = newValue;
            pBT.innerHTML = newValue;
        }
    })

四、通过addEventListener监听事件来监听input框的变化

inpBT.addEventListener('input',function(){
        data.msg=this.value
    })

效果如下

 完整代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text">
    <p></p>
</body>
<script>
    let data ={
        msg:'vue的双向数据绑定'
    }
    const inpBT = document.querySelector('input');
    const pBT = document.querySelector('p');
    inpBT.value = data.msg;
    pBT.innerHTML = data.msg;

    Object.defineProperty(data,'msg',{
        get:function(){
        },
        set:function(newValue){

            inpBT.value = newValue;
            pBT.innerHTML = newValue;
        }
    })

    inpBT.addEventListener('input',function(){
        data.msg=this.value
    })
</script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值