>  기사  >  웹 프론트엔드  >  Vue에서 지시문 기능을 구현하는 방법

Vue에서 지시문 기능을 구현하는 방법

亚连
亚连원래의
2018-06-13 15:48:031720검색

이번 글은 디렉티브의 간단한 구현을 소개하며 구현 아이디어와 코드 디자인을 주로 학습합니다. 필요한 친구들은 참고하면 됩니다

2018년 첫 번째 계획은 vue 소스 코드를 배우기로 했습니다. 커밋은 처음부터 시작해서 긴 전투가 될 것 같습니다! 이 기사에서는 지시문의 간단한 구현을 소개하고 주로 구현 아이디어와 코드 디자인을 학습합니다. 지시문과 필터는 디자인 패턴에서 "개폐 원리"를 확장하고 준수하는 데 매우 편리합니다.

API 개념

<p id="app" sd-on-click="toggle | .button">
 <p sd-text="msg | capitalize"></p>
 <p sd-class-red="error" sd-text="content"></p>
 <button class="button">Toggle class</button>
</p>
var app = Seed.create({
 id: &#39;app&#39;,
 scope: {
  msg: &#39;hello&#39;,
  content: &#39;world&#39;,
  error: true,
  toggle: function() {
   app.scope.error = !app.scope.error;
  }
 }
});

구현 기능은 간단해야 합니다. 범위의 데이터를 앱에 바인딩합니다.

핵심 논리 설계 令 명령 형식

SD-text = "msg | capitalize" 예:

SD는 통합 접두사 로고입니다. 이름

  1. capitalize는 필터 이름입니다.

  2. | 뒤에는 필터가 오고, 여러 필터를 추가할 수 있습니다.

    의 빨간색은 매개변수입니다.
  3. 코드 구조 소개

sd-class-red main.js 항목 파일

// Seed构造函数
const Seed = function(opts) {
};
// 对外暴露的API
module.exports = {
 create: function(opts) {
  return new Seed(opts);
 }
};
directives.js
module.exports = {
 text: function(el, value) {
  el.textContent = value || &#39;&#39;;
 }
};
filters.js
module.exports = {
 capitalize: function(value) {
  value = value.toString();
  return value.charAt(0).toUpperCase() + value.slice(1);
 }
};

이 세 파일만 있는데 그 중 지시문과 필터는 구성 파일이므로 확장이 쉽습니다. 일반적인 구현 아이디어는 다음과 같습니다. 1. Seed 인스턴스가 생성되면 el 컨테이너에 있는 노드 노드의 명령어가 순차적으로 구문 분석됩니다.

2 명령어 구문 분석 결과가 캡슐화됩니다. 다음 구조의 명령어 객체로:

Function🎜 바인딩🎜 🎜바인드 메소드가 지시문에 정의된 경우 bindDirective는 🎜🎜Function🎜🎜을 호출합니다.
Attribute Description type
attr 원래 속성(예: sd-text String
key ) 범위 개체 String
필터 필터 이름 목록 Array
definition text Function
argument attr에서 구문 분석된 매개변수(하나의 매개변수만 지원됨) String
update 업데이트 지시문 호출 시 def === 'function' ? def : def.updatetypeof def === 'function' ? def : def.update Function
bind 如果directive中定义了bind方法,则在bindDirective
el 存储当前element元素 Element

3.想办法执行指令的update方法即可,该插件使用了 Object.defineProperty 来定义scope中的每个属性,在其setter中触发指令的update方法。

核心代码

const prefix = &#39;sd&#39;;
const Directives = require(&#39;./directives&#39;);
const Filters = require(&#39;./filters&#39;);
// 结果为[sd-text], [sd-class], [sd-on]的字符串
const selector = Object.keys(Directives).map((name) => `[${prefix}-${name}]`).join(&#39;,&#39;);
const Seed = function(opts) {
 const self = this,
  root = this.el = document.getElementById(opts.id),
  // 筛选出el下所能支持的directive的nodes列表
  els = this.el.querySelectorAll(selector),
  bindings = {};
 this.scope = {};
 // 解析节点
 [].forEach.call(els, processNode);
 // 解析根节点
 processNode(root);
 // 给scope赋值,触发setter方法,此时会调用与其相对应的directive的update方法
 Object.keys(bindings).forEach((key) => {
  this.scope[key] = opts.scope[key];
 });
 function processNode(el) {
  cloneAttributes(el.attributes).forEach((attr) => {
   const directive = parseDirective(attr);
   if (directive) {
    bindDirective(self, el, bindings, directive);
   }
  });
 }
};

可以看到核心方法 processNode 主要做了两件事一个是 parseDirective ,另一个是 bindDirective 。

先来看看 parseDirective 方法:

function parseDirective(attr) {
 if (attr.name.indexOf(prefix) == -1) return;
 // 解析属性名称获取directive
 const noprefix = attr.name.slice(prefix.length + 1),
  argIndex = noprefix.indexOf(&#39;-&#39;),
  dirname = argIndex === -1 ? noprefix : noprefix.slice(0, argIndex),
  arg = argIndex === -1 ? null : noprefix.slice(argIndex + 1),
  def = Directives[dirname]
 // 解析属性值获取filters
 const exp = attr.value,
  pipeIndex = exp.indexOf(&#39;|&#39;),
  key = (pipeIndex === -1 ? exp : exp.slice(0, pipeIndex)).trim(),
  filters = pipeIndex === -1 ? null : exp.slice(pipeIndex + 1).split(&#39;|&#39;).map((filterName) => filterName.trim());
 return def ? {
  attr: attr,
  key: key,
  filters: filters,
  argument: arg,
  definition: Directives[dirname],
  update: typeof def === &#39;function&#39; ? def : def.update
 } : null;
}

以 sd-on-click="toggle | .button" 为例来说明,其中attr对象的name为 sd-on-click ,value为 toggle | .button ,最终解析结果为:

{
 "attr": attr,
 "key": "toggle",
 "filters": [".button"],
 "argument": "click",
 "definition": {"on": {}},
 "update": function(){}
}

紧接着调用 bindDirective 方法

/**
 * 数据绑定
 * @param {Seed} seed  Seed实例对象
 * @param {Element} el  当前node节点
 * @param {Object} bindings 数据绑定存储对象
 * @param {Object} directive 指令解析结果
 */
function bindDirective(seed, el, bindings, directive) {
 // 移除指令属性
 el.removeAttribute(directive.attr.name);
 // 数据属性
 const key = directive.key;
 let binding = bindings[key];
 if (!binding) {
  bindings[key] = binding = {
   value: undefined,
   directives: [] // 与该数据相关的指令
  };
 }
 directive.el = el;
 binding.directives.push(directive);
 if (!seed.scope.hasOwnProperty(key)) {
  bindAccessors(seed, key, binding);
 }
}
/**
 * 重写scope西乡属性的getter和setter
 * @param {Seed} seed Seed实例
 * @param {String} key  对象属性即opts.scope中的属性
 * @param {Object} binding 数据绑定关系对象
 */
function bindAccessors(seed, key, binding) {
 Object.defineProperty(seed.scope, key, {
  get: function() {
   return binding.value;
  },
  set: function(value) {
   binding.value = value;
   // 触发directive
   binding.directives.forEach((directive) => {
    // 如果有过滤器则先执行过滤器
    if (typeof value !== &#39;undefined&#39; && directive.filters) {
     value = applyFilters(value, directive);
    }
    // 调用update方法
    directive.update(directive.el, value, directive.argument, directive);
   });
  }
 });
}
/**
 * 调用filters依次处理value
 * @param {任意类型} value  数据值
 * @param {Object} directive 解析出来的指令对象
 */
function applyFilters(value, directive) {
 if (directive.definition.customFilter) {
  return directive.definition.customFilter(value, directive.filters);
 } else {
  directive.filters.forEach((name) => {
   if (Filters[name]) {
    value = Filters[name](value);
   }
  });
  return value;
 }
}

其中的bindings存放了数据和指令的关系,该对象中的key为opts.scope中的属性,value为Object,如下:

{
 "msg": {
 "value": undefined,
 "directives": [] // 上面介绍的directive对象
 }
}

数据与directive建立好关系之后, bindAccessors 中为seed的scope对象的属性重新定义了getter和setter,其中setter会调用指令update方法,到此就已经完事具备了。

Seed构造函数在实例化的最后会迭代bindings中的key,然后从opts.scope找到对应的value, 赋值给了scope对象,此时setter中的update就触发执行了。

下面再看一下 sd-on 指令的定义:

{
 on: {
  update: function(el, handler, event, directive) {
   if (!directive.handlers) {
    directive.handlers = {};
   }
   const handlers = directive.handlers;
   if (handlers[event]) {
    el.removeEventListener(event, handlers[event]);
   }
   if (handler) {
    handler = handler.bind(el);
    el.addEventListener(event, handler);
    handlers[event] = handler;
   }
  },
  customFilter: function(handler, selectors) {
   return function(e) {
    const match = selectors.every((selector) => e.target.matches(selector));
    if (match) {
     handler.apply(this, arguments);
    }
   }
  }
 }
}

发现它有customFilter,其实在 applyFilters 中就是针对该指令做的一个单独的判断,其中的selectors就是[".button"],最终返回一个匿名函数(事件监听函数),该匿名函数当做value传递给update方法,被其handler接收,update方法处理的是事件的绑定。这里其实实现的是事件的代理功能,customFilter中将handler包装一层作为事件的监听函数,同时还实现事件代理功能,设计的比较巧妙!

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在JavaScript中如何实现读取和写入cookie

在微信小程序中如何实现多文件下载

在JS中详细讲解Object对象

위 내용은 Vue에서 지시문 기능을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.