首頁  >  文章  >  web前端  >  vue的defineProperty屬性使用

vue的defineProperty屬性使用

php中世界最好的语言
php中世界最好的语言原創
2018-06-07 14:49:132805瀏覽

這次帶給大家vue的defineProperty屬性使用,vue的defineProperty屬性使用注意事項有哪些,下面就是實戰案例,一起來看一下。

1.原理

vue的雙向資料綁定的原理相信大家都十分了解;主要是透過ES5的Object物件的defineProperty屬性;重寫data的set和get函數來實現的

所以接下來不使用ES6進行實際的程式碼開發;過程中如果函數使用父級this的情況;還是使用顯示快取中間變數和閉包來處理;原因是箭頭函數沒有獨立的執行上下文this;所以箭頭函數內部出現this物件會直接存取父級;所以也能看出箭頭函數是無法完全取代function的使用場景的;例如我們需要獨立的this或是argument的時候

1.2 defineProperty是什麼

語法:

Object.defineProperty(obj, prop, descriptor)

#參數:

obj:必要的目標物件

prop:必要的需要定義或修改的屬性名稱

descriptor:必要的目標屬性全部擁有的屬性

傳回值:

傳回傳入的第一個函數;即第一個參數obj

此方法允許精確的新增或修改物件的屬性;透過賦值來新增的普通屬性會建立在屬性枚舉期間顯示(fon...in;object.key);這些新增的值可以被改變也可以刪除;也可以為這個屬性設定一些特性;例如是否只讀不可寫;目前提供兩種形式:資料描述(set;get;value;writable;enumerable;confingurable)和存取器描述(set;get)

資料描述

##當修改或定義對象的某個屬性的時候;給這個屬性添加一些特性

var obj = {
 name:'xiangha'
}
// 对象已有的属性添加特性描述
Object.defineProperty(obj,'name',{
 configurable:true | false, // 如果是false则不可以删除
 enumerable:true | false, // 如果为false则在枚举时候会忽略
 value:'任意类型的值,默认undefined'
 writable:true | false // 如果为false则不可采用数据运算符进行赋值
});
但是存在一个交叉;如果wrirable为true;而configurable为false的时候;所以需要枚举处理enumerable为false
--- 我是一个writable栗子 ---
var obj = {};
Object.defineProperty(obj,'val',{
 value:'xiangha',
 writable:false, // false
 enumerable:true,
 configurable:true
});
obj.val = '书记'; // 这个时候是更改不了a的
--- 我是一个configurable栗子 ---
var obj = {};
Object.defineProperty(obj,'val',{
 value:'xiangha',
 writable:true, // true
 enumerable:true,
 configurable:false // false
});
obj.val = '书记'; // 这个时候是val发生了改变
delete obj.val 会返回false;并且val没有删除
--- 我是一个enumerable栗子 --- 
var obj = {};
Object.defineProperty(obj,'val',{
 value:'xiangha',
 writable:true,
 enumerable:false, // false
 configurable:true
});
for(var i in obj){
 console.log(obj[i]) // 没有具体值
}
综上:对于我们有影响主要是configurable控制是否可以删除;writable控制是否可以修改赋值;enumerable是否可以枚举
所以說一旦使用Object.defineProperty()給物件添加屬性;那麼如果不設定屬性的特性;則預設值都為false

var obj = {}; 
Object.defineProperty(obj,'name',{}); // 定义了心属性name后;这个属性的特性的值都为false;这就导致name这个是不能重写不能枚举不能再次设置特性的
obj.name = '书记'; 
console.log(obj.name); // undefined
for(var i in obj){
 console.log(obj[i])
}

總結特性:

  • value:設定屬性的值

  • writable ['raɪtəbl] :值是否可以重寫

  • enumerable [ɪ'nju:mərəbəl]:目標屬性是否可以被列舉

  • configurable [kən'fɪgərəbl ]:目標屬性是否可以被刪除是否可以再次修改特性

##存取器描述

var obj = {};
Object.defineProperty(obj,'name',{
 get:function(){} | undefined,
 set:function(){} | undefined,
 configuracble:true | false,
 enumerable:true | false
})
注意:当前使用了setter和getter方法;不允许使用writable和value两个属性

gettet&& setter

#當設定取得物件的某個屬性的時候;可以提供getter和setter方法

var obj = {};
var value = 'xiangha';
Object.defineProperty(obj,'name',{
 get:function(){
  // 获取值触发
  return value
 },
 set:function(val){
  // 设置值的时候触发;设置的新值通过参数val拿到
  value = val;
 }
});
console.log(obj.name); // xiangha
obj.name = '书记';
console,.log(obj.name); // 书记

get和set不是必須成對出現對;任寫一個就行;如果不設定set和get方法;則為undefined

哈哈;前戲終於鋪墊完成了

補充:如果使用vue開發專案;嘗試去列印data物件的時候;會發現data內的每一個屬性都有get和set屬性方法;這裡說明vue和angular的雙向資料綁定不同

angular是用髒資料偵測;Model發生改變的時候;會偵測所有視圖是否綁定了相關的數據;再更新視圖

vue是使用的發布訂閱模式;點對點的綁定資料

2.實作

<p id="app">
 <form>
  <input type="text" v-model="number">
  <button type="button" v-click="increment">增加</button>
 </form>
 <h3 v-bind="number"></h3>
 </p>
頁面很簡單;包含:

    一個input,使用v-model指令
  1. 一個button,使用v-click指令
  2. 一個h3,使用v-bind指令。
  3. 我們最後也會類似vue對方式來實現雙向資料綁定
var app = new xhVue({
  el:'#app',
  data: {
  number: 0
  },
  methods: {
  increment: function() {
   this.number ++;
  },
  }
 })

2.1 定義

首先我們需要定義一個xhVue的建構子

function xhVue(options){
 
}

2.2 新增

為了初始化這個建構子;給其添加一個_init屬性

function xhVue(options){
 this._init(options);
}
xhVue.prototype._init = function(options){
 this.$options = options; // options为使用时传入的结构体;包括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; // increment
}

# 2.3 改造升級

改造_init函數;並且實作_xhob函數;對data進行處理;重寫set和get函數

xhVue.prototype._xhob = function(obj){ // obj = {number:0}
 var value;
 for(key in obj){
  if(obj.hasOwnProperty(ket)){
   value = obj[key];
   if(typeof value === 'object'){
    this._xhob(value);
   }
   Object.defineProperty(this.$data,key,{
    enumerable:true,
    configurable:true,
    get:function(){
     return value;
    },
    set:function(newVal){
     if(value !== newVal){
      value = newVal;
     }
    }
   })
  }
 }
}
xhVue.prototype._init = function(options){
 this.$options = options;
 this.$el = document.querySelector(options.el);
 this.$data = options.data;
 this.$method = options.methods;
 this._xhob(this.$data);
}

2.4 xhWatcher

指令类watcher;用来绑定更新函数;实现对DOM更新

function xhWatcher(name,el,vm,exp,attr){
 this.name = name; // 指令名称;对于文本节点;例如text
 this.el = el; // 指令对应DOM元素
 this.vm = vm; // 指令所属vue实例
 this.exp = exp; // 指令对应的值;例如number
 this.attr = attr; // 绑定的属性值;例如innerHTML
 this.update();
}
xhWatcher.prototype.update = function(){
 this.el[this.attr] = this.vm.$data[this.exp];
 // 例如h3的innerHTML = this.data.number;当numner改变则会触发本update方法;保证对应的DOM实时更新
}

2.5 完善_init和_xhob

继续完善_init和_xhob函数

// 给init的时候增加一个对象来存储model和view的映射关系;也就是我们前面定义的xhWatcher的实例;当model发生变化时;我们会触发其中的指令另其更新;保证了view也同时更新
xhVue.prototype._init = function(options){
 this.$options = options;
 this.$el = document.querySelector(options.el);
 this.$data = options.data;
 this.$method = options.methods;
 
 this._binding = {}; // _binding
 this._xhob(this.$data);
}
// 通过init出来的_binding
xhVue.prototype._xhob = function(obj){ // obj = {number:0}
 var value;
 for(key in obj){
  if(obj.hasOwnProperty(ket)){
   this._binding[key] = {
    // _binding = {number:_directives:[]}
    _directives = []
   }
   value = obj[key];
   if(typeof value === 'object'){
    this._xhob(value);
   }
   var binding = this._binding[key];
   Object.defineProperty(this.$data,key,{
    enumerable:true,
    configurable:true,
    get:function(){
     return value;
    },
    set:function(newVal){
     if(value !== newVal){
      value = newVal;
      // 当number改变时;触发_binding[number]._directives中已绑定的xhWatcher更新
      binding._directives.forEach(function(item){
       item.update(); 
      });
     }
    }
   })
  }
 }
}

2.6 解析指令

怎么才能将view与model绑定;我们定义一个_xhcomplie函数来解析我们的指令(v-bind;v-model;v-clickde)并这这个过程中对view和model进行绑定

xhVue.prototype._xhcompile = function (root) {
 // root是id为app的element的元素;也就是根元素
 var _this = this;
 var nodes = root.children;
 for (var i = 0,len = nodes.length; i < len; i++) {
  var node = nodes[i];
  if (node.children.length) {
   // 所有元素进行处理
   this._xhcompile(node)
  };
  // 如果有v-click属性;我们监听他的click事件;触发increment事件,即number++
  if (node.hasAttribute(&#39;v-click&#39;)) {
   node.onclick = (function () {
    var attrVal = nodes[i].getAttribute(&#39;v-click&#39;);
    // bind让data的作用域与methods函数的作用域保持一致
    return _this.$method[attrVal].bind(_this.$data);
   })();
  };
  // 如果有v-model属性;并且元素是input或者textrea;我们监听他的input事件
  if (node.hasAttribute(&#39;v-model&#39;) && (node.tagName = &#39;INPUT&#39; || node.tagName == &#39;TEXTAREA&#39;)) {
   node.addEventListener(&#39;input&#39;, (function (key) {
    var attrVal = node.getAttribute(&#39;v-model&#39;);
    _this._binding[attrVal]._directives.push(new xhWatcher(
     &#39;input&#39;, 
     node, 
     _this,
     attrVal, 
     &#39;value&#39;
    ));
    return function () {
     // 让number的值和node的value保持一致;就实现了双向数据绑定
     _this.$data[attrVal] = nodes[key].value
    }
   })(i));
  };
  // 如果有v-bind属性;我们要让node的值实时更新为data中number的值
  if (node.hasAttribute(&#39;v-bind&#39;)) {
   var attrVal = node.getAttribute(&#39;v-bind&#39;);
   _this._binding[attrVal]._directives.push(new xhWatcher(
    &#39;text&#39;, 
    node, 
    _this,
    attrVal,
    &#39;innerHTML&#39;
   ))
  }
 }
}

并且将解析函数也加到_init函数中

xhVue.prototype._init = function(options){
 this.$options = options;
 this.$el = document.querySelector(options.el);
 this.$data = options.data;
 this.$method = options.methods;
 
 this._binding = {}; // _binding
 this._xhob(this.$data);
 this._xhcompile(this.$el);
}

最后

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
 <p id="app">
  <form>
   <input type="text" v-model="number">
   <button type="button" v-click="increment">增加</button>
  </form>
  <h3 v-bind="number"></h3>
 </p>
</body>
<script>
 function xhVue(options) {
  this._init(options);
 }
 xhVue.prototype._init = function (options) {
  this.$options = options;
  this.$el = document.querySelector(options.el);
  this.$data = options.data;
  this.$method = options.methods;
  this._binding = {}; // _binding
  this._xhob(this.$data);
  this._xhcompile(this.$el);
 }
 xhVue.prototype._xhob = function (obj) {
  var value;
  for (key in obj) {
   if (obj.hasOwnProperty(key)) {
    this._binding[key] = {
     _directives: []
    }
    value = obj[key];
    if (typeof value === 'object') {
     this._xhob(value);
    }
    var binding = this._binding[key];
    Object.defineProperty(this.$data, key, {
     enumerable: true,
     configurable: true,
     get: function () {
      console.log(`get${value}`)
      return value;
     },
     set: function (newVal) {
      if (value !== newVal) {
       value = newVal;
       console.log(`set${newVal}`)
       // 当number改变时;触发_binding[number]._directives中已绑定的xhWatcher更新
       binding._directives.forEach(function (item) {
        item.update();
       });
      }
     }
    })
   }
  }
 }
 xhVue.prototype._xhcompile = function (root) {
  // root是id为app的element的元素;也就是根元素
  var _this = this;
  var nodes = root.children;
  for (var i = 0, len = nodes.length; i < len; i++) {
   var node = nodes[i];
   if (node.children.length) {
    // 所有元素进行处理
    this._xhcompile(node)
   };
   // 如果有v-click属性;我们监听他的click事件;触发increment事件,即number++
   if (node.hasAttribute(&#39;v-click&#39;)) {
    node.onclick = (function () {
     var attrVal = node.getAttribute(&#39;v-click&#39;);
     console.log(attrVal);
     // bind让data的作用域与method函数的作用域保持一致
     return _this.$method[attrVal].bind(_this.$data);
    })();
   };
   // 如果有v-model属性;并且元素是input或者textrea;我们监听他的input事件
   if (node.hasAttribute(&#39;v-model&#39;) && (node.tagName = &#39;INPUT&#39; || node.tagName == &#39;TEXTAREA&#39;)) {
    node.addEventListener(&#39;input&#39;, (function (key) {
     var attrVal = node.getAttribute(&#39;v-model&#39;);
     _this._binding[attrVal]._directives.push(new xhWatcher(
      &#39;input&#39;,
      node,
      _this,
      attrVal,
      &#39;value&#39;
     ));
     return function () {
      // 让number的值和node的value保持一致;就实现了双向数据绑定
      _this.$data[attrVal] = nodes[key].value
     }
    })(i));
   };
   // 如果有v-bind属性;我们要让node的值实时更新为data中number的值
   if (node.hasAttribute(&#39;v-bind&#39;)) {
    var attrVal = node.getAttribute(&#39;v-bind&#39;);
    _this._binding[attrVal]._directives.push(new xhWatcher(
     &#39;text&#39;,
     node,
     _this,
     attrVal,
     &#39;innerHTML&#39;
    ))
   }
  }
 }
 function xhWatcher(name, el, vm, exp, attr) {
  this.name = name; // 指令名称;对于文本节点;例如text
  this.el = el; // 指令对应DOM元素
  this.vm = vm; // 指令所属vue实例
  this.exp = exp; // 指令对应的值;例如number
  this.attr = attr; // 绑定的属性值;例如innerHTML
  this.update();
 }
 xhWatcher.prototype.update = function () {
  this.el[this.attr] = this.vm.$data[this.exp];
  // 例如h3的innerHTML = this.data.number;当numner改变则会触发本update方法;保证对应的DOM实时更新
 }
 var app = new xhVue({
  el: &#39;#app&#39;,
  data: {
   number: 0
  },
  methods: {
   increment: function () {
    this.number++;
   }
  }
 });
</script>
</html>

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样使用jQuery滚动条美化插件nicescroll

Angular中怎样调用第三方库

以上是vue的defineProperty屬性使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn