在使用vue時(shí)刁俭,我們?cè)谧畛鯇?duì)數(shù)據(jù)響應(yīng)式就會(huì)遇到一個(gè)概念,叫數(shù)據(jù)綁定。至于vue中怎么寫的并不是很清楚舅锄,只是知道vue2里面利用object.defineProperty方式對(duì)get/set進(jìn)行攔截。知道這個(gè)概念基本大概知道怎么去實(shí)現(xiàn)了司忱』史蓿可能不對(duì),只是在表象上進(jìn)行一次模擬坦仍。
示例如下:
代碼如下:
<!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>
<label>輸入: </label><input class="input" /><br />
<label>輸出: </label><span class="output"></span><br />
<label>輸出: </label><span class="output"></span><br />
<label>輸出: </label><span class="output"></span><br />
<script>
window.viewModel = {};
let input = document.querySelector('.input');
let outputs = document.querySelectorAll('.output');
Object.defineProperty(viewModel, 'inputValue', {
enumerable: true,
configurable: true,
get: function () {
return input.value;
},
set: function (value) {
input.value = value;
inputListener(value);
}
});
const eventNames = ['input', 'change'];
eventNames.forEach(eventName => {
input.addEventListener(eventName, function (e) {
window.viewModel.inputValue = e.target.value;
});
});
inputListener = function (value) {
outputs.forEach(output => {
output.innerHTML = value;
});
}
</script>
</body>
</html>
知識(shí)點(diǎn)
Object.defineProperty
給某一對(duì)象添加屬性鳍烁,并且可以設(shè)置get/set屬性
input.addEventListener
給屬性添加事件見監(jiān)聽
該實(shí)例利用攔截get/set方法,實(shí)現(xiàn)與output之間的數(shù)據(jù)綁定繁扎。