UNPKG

eslint-plugin-vue

Version:

Official ESLint plugin for Vue.js

74 lines (73 loc) • 2.44 kB
const require_index = require("../utils/index.js"); const require_js_reserved = require("../utils/js-reserved.json.js"); // lib/rules/this-in-template.ts /** * @fileoverview disallow usage of `this` in template. * @author Armano */ const RESERVED_NAMES = new Set(require_js_reserved.default); var this_in_template_default = { meta: { type: "suggestion", docs: { description: "disallow usage of `this` in template", categories: ["vue3-recommended", "vue2-recommended"], url: "https://eslint.vuejs.org/rules/this-in-template.html" }, fixable: "code", schema: [{ enum: ["always", "never"] }], messages: { unexpected: "Unexpected usage of 'this'.", expected: "Expected 'this'." } }, /** * Creates AST event handlers for this-in-template. */ create(context) { const options = context.options[0] === "always" ? "always" : "never"; let scopeStack = null; return require_index.default.defineTemplateBodyVisitor(context, { VElement(node) { scopeStack = { parent: scopeStack, nodes: scopeStack ? [...scopeStack.nodes] : [] }; if (node.variables) for (const variable of node.variables) { const varNode = variable.id; const name = varNode.name; if (scopeStack.nodes.every((node) => node.name !== name)) scopeStack.nodes.push(varNode); } }, "VElement:exit"() { scopeStack &&= scopeStack.parent; }, ...options === "never" ? { "VExpressionContainer MemberExpression > ThisExpression"(node) { if (!scopeStack) return; const propertyName = require_index.default.getStaticPropertyName(node.parent); if (!propertyName || scopeStack.nodes.some((el) => el.name === propertyName) || RESERVED_NAMES.has(propertyName) || /^\d.*$|[^\w$]/.test(propertyName)) return; context.report({ node, loc: node.loc, fix(fixer) { return fixer.replaceText(node.parent, propertyName); }, messageId: "unexpected" }); } } : { VExpressionContainer(node) { if (!scopeStack || node.parent.type === "VDirectiveKey") return; if (node.references) { for (const reference of node.references) if (scopeStack.nodes.every((el) => el.name !== reference.id.name)) context.report({ node: reference.id, loc: reference.id.loc, messageId: "expected", fix(fixer) { return fixer.insertTextBefore(reference.id, "this."); } }); } } } }); } }; exports.default = this_in_template_default;