双向数据绑定

Vue中的双向数据绑定

Vue 最核心的功能有两个,一是响应式的数据绑定系统,二是组件化。来看下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-model="text">
<span>{{text}}</span>
</div>
<script src="node_modules/vue/dist/vue.min.js"></script>
<script>
new Vue({
el: "#app",
data: {
text: "hello, world!"
}
})
</script>
</body>
</html>

在浏览器中运行可以看到,随文本框输入文字的变化,span 中会同步显示相同的文字内容.这就是 Vue 中 model => view 以及 view => model 的双向数据绑定,如下图所示:
alt

实现简单的双向数据绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="input">
<span id="span"></span>
<script>
let obj = {};
let inputEle = document.getElementById('input');
let spanEle = document.getElementById('span');
// 数据劫持
Object.defineProperty(obj, 'text', {
configurable: true,
enumerable: true,
get() {
console.log('获取数据了');
},
set(newVal) {
console.log('数据更新了');
inputEle.value = newVal;
spanEle.innerHTML = newVal;
}
});
// 输入监听
inputEle.addEventListener('keyup', function (e) {
obj.text = e.target.value;
});
</script>
</body>
</html>

在浏览器中运行此代码可以看到:随文本框输入文字的变化,span 中会同步显示相同的文字内容;在js或控制台显式的修改 obj.text 的值,视图会相应更新。这样就实现了 model => view 以及 view => model 的双向数据绑定,如下图所示:
alt

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020-2021 Sanmu
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信