ホームページ ウェブフロントエンド jsチュートリアル Vueでディレクティブ関数を実装する方法

Vueでディレクティブ関数を実装する方法

Jun 13, 2018 pm 03:48 PM
directive vue

この記事では、ディレクティブの簡単な実装を紹介し、主にその実装アイデアとコード設計を学習します。必要な友人はそれを参照してください。

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);
 }
};
ログイン後にコピー

この3つのファイルのみ、ディレクティブとフィルターは拡張が簡単な設定ファイルです。 実装の一般的な考え方は次のとおりです: 1. Seed インスタンスが作成されると、el コンテナ内のノードの命令が順番に解析されます

2.次の構造を持つ命令オブジェクトにカプセル化されます:

内 bind 🎜bind メソッドがディレクティブで定義されている場合、bindDirective が呼び出されます🎜🎜
AttributeDescriptiontype
attr属性名に対応するsd-textString
keyなどスコープオブジェクトString
フィルターフィルター名リスト配列
定義テキストに対応する関数などのこのディレクティブの定義関数
引数attrから解析されたパラメータ(1つのパラメータのみがサポートされます)文字列
更新ディレクティブの更新 typeof def === 'function' ? def : def.updatetypeof def === &#39;function&#39; ? def : def.updateFunction
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 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

VUEのボタンに関数を追加する方法 VUEのボタンに関数を追加する方法 Apr 08, 2025 am 08:51 AM

HTMLテンプレートのボタンをメソッドにバインドすることにより、VUEボタンに関数を追加できます。 VUEインスタンスでメソッドを定義し、関数ロジックを書き込みます。

VueでBootstrapの使用方法 VueでBootstrapの使用方法 Apr 07, 2025 pm 11:33 PM

vue.jsでBootstrapを使用すると、5つのステップに分かれています。ブートストラップをインストールします。 main.jsにブートストラップをインポートしますブートストラップコンポーネントをテンプレートで直接使用します。オプション:カスタムスタイル。オプション:プラグインを使用します。

vue.jsでJSファイルを参照する方法 vue.jsでJSファイルを参照する方法 Apr 07, 2025 pm 11:27 PM

vue.jsでJSファイルを参照するには3つの方法があります。タグ;; mounted()ライフサイクルフックを使用した動的インポート。 Vuex State Management Libraryを介してインポートします。

VueでWatchの使用方法 VueでWatchの使用方法 Apr 07, 2025 pm 11:36 PM

Vue.jsの監視オプションにより、開発者は特定のデータの変更をリッスンできます。データが変更されたら、Watchはコールバック関数をトリガーして更新ビューまたはその他のタスクを実行します。その構成オプションには、すぐにコールバックを実行するかどうかを指定する即時と、オブジェクトまたは配列の変更を再帰的に聴くかどうかを指定するDEEPが含まれます。

Vueによる前のページに戻る方法 Vueによる前のページに戻る方法 Apr 07, 2025 pm 11:30 PM

vue.jsには、前のページに戻る4つの方法があります。$ router.go(-1)$ router.back()outes&lt; router-link to =&quot;/&quot; Component Window.history.back()、およびメソッド選択はシーンに依存します。

Vueのバージョンを照会する方法 Vueのバージョンを照会する方法 Apr 07, 2025 pm 11:24 PM

Vue Devtoolsを使用してブラウザのコンソールでVueタブを表示することにより、Vueバージョンを照会できます。 NPMを使用して、「NPM List -G Vue」コマンドを実行します。 package.jsonファイルの「依存関係」オブジェクトでVueアイテムを見つけます。 Vue CLIプロジェクトの場合、「Vue -Version」コマンドを実行します。 &lt; script&gt;でバージョン情報を確認してくださいVueファイルを参照するHTMLファイルにタグを付けます。

Vue Multi-Page開発とはどういう意味ですか? Vue Multi-Page開発とはどういう意味ですか? Apr 07, 2025 pm 11:57 PM

VUEマルチページ開発は、VUE.JSフレームワークを使用してアプリケーションを構築する方法です。アプリケーションは別々のページに分割されます。コードメンテナンス:アプリケーションを複数のページに分割すると、コードの管理とメンテナンスが容易になります。モジュール性:各ページは、簡単に再利用および交換するための別のモジュールとして使用できます。簡単なルーティング:ページ間のナビゲーションは、単純なルーティング構成を介して管理できます。 SEOの最適化:各ページには独自のURLがあり、SEOに役立ちます。

VueのDivにジャンプする方法 VueのDivにジャンプする方法 Apr 08, 2025 am 09:18 AM

VUEにDIV要素をジャンプするには、VUEルーターを使用してルーターリンクコンポーネントを追加するには、2つの方法があります。 @clickイベントリスナーを追加して、これを呼び出します。$ router.push()メソッドをジャンプします。

See all articles