Madogiwa Blog

主に技術系の学習メモに使っていきます。

カスタムコンポーネントへの`v-model`の利用を`eslint-plugin-vue`のカスタムルールで検知するメモ📝

Vue3アップデートの破壊的変更として以下のカスタムコンポーネントv-modelに関するものがあり結構影響範囲が広そうで何かソリューション無いかなと思っていたのですが、

v3-migration.vuejs.org

eslint-plugin-vueのカスタムルールを作れば意外と簡単にカスタムコンポーネントv-modelの利用箇所を特定できそうだったので作成したカスタムルールをメモがてら記載してきます📝

以下がそのコードで適当なディレクトリに配置し、ESLintの設定ファイルから有効化すればカスタムコンポーネントへのv-modelの利用を検知できます。

VAttribute[directive=true][key.name.name='model'v-modelが記載されている要素の属性にアクセスし、utils.isCustomComponent(node.parent.parent)で属性から要素へ辿ってカスタムコンポーネントかどうかを判定し、カスタムコンポーネントだったらreportするようにしています。

/**
 * @author madogiwa
 * See LICENSE file in root directory for full license.
 */
"use strict";

const utils = require("eslint-plugin-vue/lib/utils");

module.exports = {
  meta: {
    type: "problem",
    docs: {
      description: "disallow using v-model for custom component is affected by a breaking change in Vue3.",
      categories: undefined,
      url: "https://eslint.vuejs.org/rules/no-use-v-model-for-custom-component.html",
    },
    fixable: null,
    schema: [],
    messages: {
      error: "Using v-model for custom component is affected by a breaking change in Vue3.",
    },
  },
  /** @param {RuleContext} context */
  create(context) {
    return utils.defineTemplateBodyVisitor(context, {
      "VAttribute[directive=true][key.name.name='model']"(node) {
        if (utils.isCustomComponent(node.parent.parent)) {
          context.report({
            node,
            loc: node.loc,
            messageId: "error",
          });
        }
      },
    });
  },
};

ESLintのカスタムルールを有効化する方法等々は以前記事を書いているので参考までに🔖

madogiwa0124.hatenablog.com

eslint-plugin-vue便利ですね!!

github.com