1. 程式人生 > >Vue雙向綁定簡單實現

Vue雙向綁定簡單實現

http 代碼 mode fun nod object target input class

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>雙向綁定簡單實現</title>
</head>
<body>
  
  <div id="app">
    <input type="text" v-model="text">
    {{ text }}
  </div>

  <script>
    function observe (obj, vm) {
      Object.keys(obj).forEach(
function (key) { defineReactive(vm, key, obj[key]); }); } function defineReactive (obj, key, val) { var dep = new Dep(); Object.defineProperty(obj, key, { get: function () { // 添加訂閱者watcher到主題對象Dep if (Dep.target) dep.addSub(Dep.target);
return val }, set: function (newVal) { if (newVal === val) return val = newVal; // 作為發布者發出通知 dep.notify(); } }); } function nodeToFragment (node, vm) { var flag = document.createDocumentFragment();
var child; while (child = node.firstChild) { compile(child, vm); flag.appendChild(child); // 將子節點劫持到文檔片段中 } return flag; } function compile (node, vm) { var reg = /\{\{(.*)\}\}/; // 節點類型為元素 if (node.nodeType === 1) { var attr = node.attributes; // 解析屬性 for (var i = 0; i < attr.length; i++) { if (attr[i].nodeName == ‘v-model‘) { var name = attr[i].nodeValue; // 獲取v-model綁定的屬性名 node.addEventListener(‘input‘, function (e) { // 給相應的data屬性賦值,進而觸發該屬性的set方法 vm[name] = e.target.value; }); node.value = vm[name]; // 將data的值賦給該node node.removeAttribute(‘v-model‘); } }; new Watcher(vm, node, name, ‘input‘); } // 節點類型為text if (node.nodeType === 3) { if (reg.test(node.nodeValue)) { var name = RegExp.$1; // 獲取匹配到的字符串 name = name.trim(); new Watcher(vm, node, name, ‘text‘); } } } function Watcher (vm, node, name, nodeType) { Dep.target = this; this.name = name; this.node = node; this.vm = vm; this.nodeType = nodeType; this.update(); Dep.target = null; } Watcher.prototype = { update: function () { this.get(); if (this.nodeType == ‘text‘) { this.node.nodeValue = this.value; } if (this.nodeType == ‘input‘) { this.node.value = this.value; } }, // 獲取data中的屬性值 get: function () { this.value = this.vm[this.name]; // 觸發相應屬性的get } } function Dep () { this.subs = [] } Dep.prototype = { addSub: function(sub) { this.subs.push(sub); }, notify: function() { this.subs.forEach(function(sub) { sub.update(); }); } }; function Vue (options) { this.data = options.data; var data = this.data; observe(data, this); var id = options.el; var dom = nodeToFragment(document.getElementById(id), this); // 編譯完成後,將dom返回到app中 document.getElementById(id).appendChild(dom); } var vm = new Vue({ el: ‘app‘, data: { text: ‘hello world‘ } }); </script> </body> </html>

技術分享

轉載自:http://www.cnblogs.com/kidney/p/6052935.html 代碼 解釋 這裏

Vue雙向綁定簡單實現