vue 中directive功能的简单实现


Posted in Javascript onJanuary 05, 2018

2018年首个计划是学习vue源码,查阅了一番资料之后,决定从第一个commit开始看起,这将是一场持久战!本篇介绍directive的简单实现,主要学习其实现的思路及代码的设计(directive和filter扩展起来非常方便,符合设计模式中的 开闭原则 )。

构思API

<div 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>
</div>
var app = Seed.create({
 id: 'app',
 scope: {
  msg: 'hello',
  content: 'world',
  error: true,
  toggle: function() {
   app.scope.error = !app.scope.error;
  }
 }
});

实现功能够简单吧--将scope中的数据绑定到app中。

核心逻辑设计

指令格式

以 sd-text="msg | capitalize" 为例说明:

  1. sd 为统一的前缀标识
  2. text 为指令名称
  3. capitalize 为过滤器名称

其中 | 后面为过滤器,可以添加多个。 sd-class-red 中的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 || '';
 }
};
filters.js
module.exports = {
 capitalize: function(value) {
  value = value.toString();
  return value.charAt(0).toUpperCase() + value.slice(1);
 }
};

就这三个文件,其中directives和filters都是配置文件,很易于扩展。

实现的大致思路如下:

1.在Seed实例创建的时候会依次解析el容器中node节点的指令

2.将指令解析结果封装为指令对象,结构为:

属性 说明 类型
attr 原始属性,如 sd-text String
key 对应scope对象中的属性名称 String
filters 过滤器名称列表 Array
definition 该指令的定义,如text对应的函数 Function
argument 从attr中解析出来的参数(只支持一个参数) String
update 更新directive时调用 typeof def === 'function' ? def : def.update Function
bind 如果directive中定义了bind方法,则在 bindDirective 中会调用 Function
el 存储当前element元素 Element

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

核心代码

const prefix = 'sd';
const Directives = require('./directives');
const Filters = require('./filters');
// 结果为[sd-text], [sd-class], [sd-on]的字符串
const selector = Object.keys(Directives).map((name) => `[${prefix}-${name}]`).join(',');
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('-'),
  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('|'),
  key = (pipeIndex === -1 ? exp : exp.slice(0, pipeIndex)).trim(),
  filters = pipeIndex === -1 ? null : exp.slice(pipeIndex + 1).split('|').map((filterName) => filterName.trim());
 return def ? {
  attr: attr,
  key: key,
  filters: filters,
  argument: arg,
  definition: Directives[dirname],
  update: typeof def === 'function' ? 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 !== 'undefined' && 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包装一层作为事件的监听函数,同时还实现事件代理功能,设计的比较巧妙!

总结

以上所述是小编给大家介绍的vue 中directive的简单实现,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
(jQuery,mootools,dojo)使用适合自己的编程别名命名
Sep 14 Javascript
jQuery操作select下拉框的text值和value值的方法
May 31 Javascript
JS实现页面数据无限加载
Sep 13 Javascript
jquery事件绑定解绑机制源码解析
Sep 19 Javascript
JS基于正则实现数字千分位用逗号分隔的方法
Jun 16 Javascript
bootstrap时间控件daterangepicker使用方法及各种小bug修复
Oct 25 Javascript
详解node.js 下载图片的 2 种方式
Mar 02 Javascript
原生JS实现前端本地文件上传
Sep 08 Javascript
vue实现条件判断动态绑定样式的方法
Sep 29 Javascript
js实现简单掷骰子效果
Oct 24 Javascript
24个解决实际问题的ES6代码片段(小结)
Feb 02 Javascript
基于javascript实现移动端轮播图效果
Dec 21 Javascript
浅谈React前后端同构防止重复渲染
Jan 05 #Javascript
使用vue实现grid-layout功能实例代码
Jan 05 #Javascript
详解为Bootstrap Modal添加拖拽的方法
Jan 05 #Javascript
JS交互点击WKWebView中的图片实现预览效果
Jan 05 #Javascript
Vue组件的使用教程详解
Jan 05 #Javascript
基于three.js编写的一个项目类示例代码
Jan 05 #Javascript
js中this对象用法分析
Jan 05 #Javascript
You might like
PHP 函数执行效率的小比较
2010/10/17 PHP
PHP日志LOG类定义与用法示例
2018/09/06 PHP
Laravel框架基础语法与知识点整理【模板变量、输出、include引入子视图等】
2019/12/03 PHP
js实现div的切换特效上一个下一个
2014/02/11 Javascript
使用JavaScript判断图片是否加载完成的三种实现方式
2014/05/04 Javascript
javascript搜索框点击文字消失失焦时文本出现
2014/09/18 Javascript
浅析javascript异步执行函数导致的变量变化问题解决思路
2016/05/13 Javascript
jquery easyui validatebox remote的使用详解
2016/11/09 Javascript
Vue.js双向绑定操作技巧(初级入门)
2016/12/27 Javascript
React.js中常用的ES6写法总结(推荐)
2017/05/09 Javascript
详解用vue编写弹出框组件
2017/07/04 Javascript
微信小程序methods中定义的方法互相调用的实例代码
2018/08/07 Javascript
微信{"errcode":48001,"errmsg":"api unauthorized, hints: [ req_id: 1QoCla0699ns81 ]"}
2018/10/12 Javascript
用VueJS写一个Chrome浏览器插件的实现方法
2019/02/27 Javascript
基于vue-cli 路由 实现类似tab切换效果(vue 2.0)
2019/05/08 Javascript
Django中模版的子目录与include标签的使用方法
2015/07/16 Python
Pandas之排序函数sort_values()的实现
2019/07/09 Python
python实现切割url得到域名、协议、主机名等各个字段的例子
2019/07/25 Python
Jupyter打开图形界面并画出正弦函数图像实例
2020/04/24 Python
python实现二分类和多分类的ROC曲线教程
2020/06/15 Python
Python extract及contains方法代码实例
2020/09/11 Python
Python模块常用四种安装方式
2020/10/20 Python
Python 排序最长英文单词链(列表中前一个单词末字母是下一个单词的首字母)
2020/12/14 Python
详解Python中的GIL(全局解释器锁)详解及解决GIL的几种方案
2021/01/29 Python
美国乡村商店:Plow & Hearth
2016/09/12 全球购物
美国著名手表网站:Timepiece
2017/11/15 全球购物
马来西亚综合购物网站:Lazada马来西亚
2018/06/05 全球购物
员工培训邀请函
2014/01/11 职场文书
课堂教学改革实施方案
2014/03/17 职场文书
土地转让协议书范本
2014/04/15 职场文书
计算机专业自荐信范文
2014/05/28 职场文书
护士求职简历自我评价
2015/03/10 职场文书
2015年安全月活动总结
2015/03/26 职场文书
求职意向书范本
2015/05/11 职场文书
SpringBoot+Vue+JWT的前后端分离登录认证详细步骤
2021/09/25 Java/Android
Win10鼠标宏怎么设置?win10系统鼠标宏的设置方法
2022/08/14 数码科技