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>