最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Vue如何寫一個雙向數(shù)據(jù)綁定(面試常見)

 更新時間:2018年04月20日 10:21:19   作者:呆頭呆腦丶  
這篇文章主要介紹了使用Vue如何寫一個雙向數(shù)據(jù)綁定,在前端面試過程中經(jīng)常會問到,文中主要實(shí)現(xiàn)v-model,v-bind 和v-click三個命令,其他命令也可以自行補(bǔ)充。需要的朋友可以參考下

1、原理

Vue的雙向數(shù)據(jù)綁定的原理相信大家也都十分了解了,主要是通過 Object對象的defineProperty屬性,重寫data的set和get函數(shù)來實(shí)現(xiàn)的,這里對原理不做過多描述,主要還是來實(shí)現(xiàn)一個實(shí)例。為了使代碼更加的清晰,這里只會實(shí)現(xiàn)最基本的內(nèi)容,主要實(shí)現(xiàn)v-model,v-bind 和v-click三個命令,其他命令也可以自行補(bǔ)充。

添加網(wǎng)上的一張圖

2、實(shí)現(xiàn)

頁面結(jié)構(gòu)很簡單,如下

<div id="app">
 <form>
  <input type="text" v-model="number">
  <button type="button" v-click="increment">增加</button>
 </form>
 <h3 v-bind="number"></h3>
 </div>

包含:

 1. 一個input,使用v-model指令
 2. 一個button,使用v-click指令
 3. 一個h3,使用v-bind指令。

我們最后會通過類似于vue的方式來使用我們的雙向數(shù)據(jù)綁定,結(jié)合我們的數(shù)據(jù)結(jié)構(gòu)添加注釋

var app = new myVue({
  el:'#app',
  data: {
  number: 0
  },
  methods: {
  increment: function() {
   this.number ++;
  },
  }
 })

首先我們需要定義一個myVue構(gòu)造函數(shù):

function myVue(options) {
}

為了初始化這個構(gòu)造函數(shù),給它添加一 個_init屬性

function myVue(options) {
 this._init(options);
}
myVue.prototype._init = function (options) {
 this.$options = options; // options 為上面使用時傳入的結(jié)構(gòu)體,包括el,data,methods
 this.$el = document.querySelector(options.el); // el是 #app, this.$el是id為app的Element元素
 this.$data = options.data; // this.$data = {number: 0}
 this.$methods = options.methods; // this.$methods = {increment: function(){}}
 }

接下來實(shí)現(xiàn)_obverse函數(shù),對data進(jìn)行處理,重寫data的set和get函數(shù)

并改造_init函數(shù)

myVue.prototype._obverse = function (obj) { // obj = {number: 0}
 var value;
 for (key in obj) { //遍歷obj對象
  if (obj.hasOwnProperty(key)) {
  value = obj[key]; 
  if (typeof value === 'object') { //如果值還是對象,則遍歷處理
   this._obverse(value);
  }
  Object.defineProperty(this.$data, key, { //關(guān)鍵
   enumerable: true,
   configurable: true,
   get: function () {
   console.log(`獲取${value}`);
   return value;
   },
   set: function (newVal) {
   console.log(`更新${newVal}`);
   if (value !== newVal) {
    value = newVal;
   }
   }
  })
  }
 }
 }
 myVue.prototype._init = function (options) {
 this.$options = options;
 this.$el = document.querySelector(options.el);
 this.$data = options.data;
 this.$methods = options.methods;
 this._obverse(this.$data);
 }

接下來我們寫一個指令類Watcher,用來綁定更新函數(shù),實(shí)現(xiàn)對DOM元素的更新

function Watcher(name, el, vm, exp, attr) {
 this.name = name;   //指令名稱,例如文本節(jié)點(diǎn),該值設(shè)為"text"
 this.el = el;    //指令對應(yīng)的DOM元素
 this.vm = vm;    //指令所屬myVue實(shí)例
 this.exp = exp;   //指令對應(yīng)的值,本例如"number"
 this.attr = attr;   //綁定的屬性值,本例為"innerHTML"
 this.update();
 }
 Watcher.prototype.update = function () {
 this.el[this.attr] = this.vm.$data[this.exp]; //比如 H3.innerHTML = this.data.number; 當(dāng)number改變時,會觸發(fā)這個update函數(shù),保證對應(yīng)的DOM內(nèi)容進(jìn)行了更新。
 }

更新_init函數(shù)以及_obverse函數(shù)

myVue.prototype._init = function (options) {
 //...
 this._binding = {}; //_binding保存著model與view的映射關(guān)系,也就是我們前面定義的Watcher的實(shí)例。當(dāng)model改變時,我們會觸發(fā)其中的指令類更新,保證view也能實(shí)時更新
 //...
 }
 myVue.prototype._obverse = function (obj) {
 //...
  if (obj.hasOwnProperty(key)) {
  this._binding[key] = { // 按照前面的數(shù)據(jù),_binding = {number: _directives: []}                                     
   _directives: []
  };
  //...
  var binding = this._binding[key];
  Object.defineProperty(this.$data, key, {
   //...
   set: function (newVal) {
   console.log(`更新${newVal}`);
   if (value !== newVal) {
    value = newVal;
    binding._directives.forEach(function (item) { // 當(dāng)number改變時,觸發(fā)_binding[number]._directives 中的綁定的Watcher類的更新
    item.update();
    })
   }
   }
  })
  }
 }
 }

那么如何將view與model進(jìn)行綁定呢?接下來我們定義一個_compile函數(shù),用來解析我們的指令(v-bind,v-model,v-clickde)等,并在這個過程中對view與model進(jìn)行綁定。

 myVue.prototype._init = function (options) {
 //...
 this._complie(this.$el);
 }
myVue.prototype._complie = function (root) { root 為 id為app的Element元素,也就是我們的根元素
 var _this = this;
 var nodes = root.children;
 for (var i = 0; i < nodes.length; i++) {
  var node = nodes[i];
  if (node.children.length) { // 對所有元素進(jìn)行遍歷,并進(jìn)行處理
  this._complie(node);
  }
  if (node.hasAttribute('v-click')) { // 如果有v-click屬性,我們監(jiān)聽它的onclick事件,觸發(fā)increment事件,即number++
  node.onclick = (function () {
   var attrVal = nodes[i].getAttribute('v-click');
   return _this.$methods[attrVal].bind(_this.$data); //bind是使data的作用域與method函數(shù)的作用域保持一致
  })();
  }
  if (node.hasAttribute('v-model') && (node.tagName == 'INPUT' || node.tagName == 'TEXTAREA')) { // 如果有v-model屬性,并且元素是INPUT或者TEXTAREA,我們監(jiān)聽它的input事件
  node.addEventListener('input', (function(key) { 
   var attrVal = node.getAttribute('v-model');
   //_this._binding['number']._directives = [一個Watcher實(shí)例]
   // 其中Watcher.prototype.update = function () {
   // node['vaule'] = _this.$data['number']; 這就將node的值保持與number一致
   // }
   _this._binding[attrVal]._directives.push(new Watcher( 
   'input',
   node,
   _this,
   attrVal,
   'value'
   ))
   return function() {
   _this.$data[attrVal] = nodes[key].value; // 使number 的值與 node的value保持一致,已經(jīng)實(shí)現(xiàn)了雙向綁定
   }
  })(i));
  } 
  if (node.hasAttribute('v-bind')) { // 如果有v-bind屬性,我們只要使node的值及時更新為data中number的值即可
  var attrVal = node.getAttribute('v-bind');
  _this._binding[attrVal]._directives.push(new Watcher(
   'text',
   node,
   _this,
   attrVal,
   'innerHTML'
  ))
  }
 }
 }

至此,我們已經(jīng)實(shí)現(xiàn)了一個簡單vue的雙向綁定功能,包括v-bind, v-model, v-click三個指令。效果如下圖

附上全部代碼,不到150行

<!DOCTYPE html>
<head>
 <title>myVue</title>
</head>
<style>
 #app {
 text-align: center;
 }
</style>
<body>
 <div id="app">
 <form>
  <input type="text" v-model="number">
  <button type="button" v-click="increment">增加</button>
 </form>
 <h3 v-bind="number"></h3>
 </div>
</body>
<script>
 function myVue(options) {
 this._init(options);
 }
 myVue.prototype._init = function (options) {
 this.$options = options;
 this.$el = document.querySelector(options.el);
 this.$data = options.data;
 this.$methods = options.methods;
 this._binding = {};
 this._obverse(this.$data);
 this._complie(this.$el);
 }
 myVue.prototype._obverse = function (obj) {
 var value;
 for (key in obj) {
  if (obj.hasOwnProperty(key)) {
  this._binding[key] = {                                       
   _directives: []
  };
  value = obj[key];
  if (typeof value === 'object') {
   this._obverse(value);
  }
  var binding = this._binding[key];
  Object.defineProperty(this.$data, key, {
   enumerable: true,
   configurable: true,
   get: function () {
   console.log(`獲取${value}`);
   return value;
   },
   set: function (newVal) {
   console.log(`更新${newVal}`);
   if (value !== newVal) {
    value = newVal;
    binding._directives.forEach(function (item) {
    item.update();
    })
   }
   }
  })
  }
 }
 }
 myVue.prototype._complie = function (root) {
 var _this = this;
 var nodes = root.children;
 for (var i = 0; i < nodes.length; i++) {
  var node = nodes[i];
  if (node.children.length) {
  this._complie(node);
  }
  if (node.hasAttribute('v-click')) {
  node.onclick = (function () {
   var attrVal = nodes[i].getAttribute('v-click');
   return _this.$methods[attrVal].bind(_this.$data);
  })();
  }
  if (node.hasAttribute('v-model') && (node.tagName == 'INPUT' || node.tagName == 'TEXTAREA')) {
  node.addEventListener('input', (function(key) {
   var attrVal = node.getAttribute('v-model');
   _this._binding[attrVal]._directives.push(new Watcher(
   'input',
   node,
   _this,
   attrVal,
   'value'
   ))
   return function() {
   _this.$data[attrVal] = nodes[key].value;
   }
  })(i));
  } 
  if (node.hasAttribute('v-bind')) {
  var attrVal = node.getAttribute('v-bind');
  _this._binding[attrVal]._directives.push(new Watcher(
   'text',
   node,
   _this,
   attrVal,
   'innerHTML'
  ))
  }
 }
 }
 function Watcher(name, el, vm, exp, attr) {
 this.name = name;   //指令名稱,例如文本節(jié)點(diǎn),該值設(shè)為"text"
 this.el = el;    //指令對應(yīng)的DOM元素
 this.vm = vm;    //指令所屬myVue實(shí)例
 this.exp = exp;   //指令對應(yīng)的值,本例如"number"
 this.attr = attr;   //綁定的屬性值,本例為"innerHTML"
 this.update();
 }
 Watcher.prototype.update = function () {
 this.el[this.attr] = this.vm.$data[this.exp];
 }
 window.onload = function() {
 var app = new myVue({
  el:'#app',
  data: {
  number: 0
  },
  methods: {
  increment: function() {
   this.number ++;
  },
  }
 })
 }
</script>

總結(jié)

以上所述是小編給大家介紹的使用Vue如何寫一個雙向數(shù)據(jù)綁定(面試常見),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • vue 實(shí)現(xiàn)購物車總價計(jì)算

    vue 實(shí)現(xiàn)購物車總價計(jì)算

    今天小編就為大家分享一篇vue 實(shí)現(xiàn)購物車總價計(jì)算,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • elementUI動態(tài)表單?+?el-select?按要求禁用問題

    elementUI動態(tài)表單?+?el-select?按要求禁用問題

    這篇文章主要介紹了elementUI動態(tài)表單?+?el-select?按要求禁用問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • vue中的echarts實(shí)現(xiàn)寬度自適應(yīng)的解決方案

    vue中的echarts實(shí)現(xiàn)寬度自適應(yīng)的解決方案

    這篇文章主要介紹了vue中的echarts實(shí)現(xiàn)寬度自適應(yīng),本文給大家分享實(shí)現(xiàn)方案,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-09-09
  • 詳解基于vue-cli優(yōu)化的webpack配置

    詳解基于vue-cli優(yōu)化的webpack配置

    本篇文章主要介紹了詳解基于vue-cli優(yōu)化的webpack配置,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-11-11
  • 詳解element-ui中el-select的默認(rèn)選擇項(xiàng)問題

    詳解element-ui中el-select的默認(rèn)選擇項(xiàng)問題

    這篇文章主要介紹了詳解element-ui中el-select的默認(rèn)選擇項(xiàng)問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • webstorm和.vue中es6語法報(bào)錯的解決方法

    webstorm和.vue中es6語法報(bào)錯的解決方法

    本篇文章主要介紹了webstorm和.vue中es6語法報(bào)錯的解決方法,小編總結(jié)了webstorm和.vue中出現(xiàn)的es6語法報(bào)錯,避免大家采坑,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • 關(guān)閉eslint檢查和ts檢查的簡單步驟記錄

    關(guān)閉eslint檢查和ts檢查的簡單步驟記錄

    這篇文章主要給大家介紹了關(guān)于關(guān)閉eslint檢查和ts檢查的相關(guān)資料,eslint是一個JavaScript的校驗(yàn)插件,通常用來校驗(yàn)語法或代碼的書寫風(fēng)格,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-02-02
  • vue watch監(jiān)聽數(shù)據(jù)變化的案例詳解

    vue watch監(jiān)聽數(shù)據(jù)變化的案例詳解

    監(jiān)聽數(shù)據(jù)變化,在Vue中是通過偵聽器來實(shí)現(xiàn)的,你也可以將它理解為監(jiān)聽器,時刻監(jiān)聽某個數(shù)據(jù)的變化,本文將通過代碼示例為大家詳細(xì)的介紹一下vue watch如何監(jiān)聽數(shù)據(jù)變化,需要的朋友可以參考下
    2023-07-07
  • vue pdf二次封裝解決無法顯示中文問題方法詳解

    vue pdf二次封裝解決無法顯示中文問題方法詳解

    這篇文章主要為大家介紹了vue pdf二次封裝解決無法顯示中文問題方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-01-01
  • vue3.0生命周期的示例代碼

    vue3.0生命周期的示例代碼

    這篇文章主要介紹了vue3.0生命周期的相關(guān)知識,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2020-09-09

最新評論

勃利县| 明光市| 阜南县| 卢龙县| 云阳县| 柏乡县| 宁城县| 三门峡市| 务川| 泌阳县| 修水县| 大新县| 梧州市| 新沂市| 宝坻区| 大宁县| 舒兰市| 清镇市| 南溪县| 蚌埠市| 新兴县| 壶关县| 永登县| 安达市| 哈巴河县| 昔阳县| 莱州市| 玛纳斯县| 金寨县| 夏河县| 吴堡县| 丰城市| 高碑店市| 茂名市| 渝中区| 阿拉善右旗| 衡东县| 巨鹿县| 庆安县| 四子王旗| 永宁县|