Custom instruction

In addition to the core functionality’s default built-in directives (such as V-model and V-show), Vue also allows you to register custom directives. Note that in Vue, the main form of code reuse and abstraction is components.

Vue3.0 hook functions

  • created: called before the attribute or event listener of the bound element is applied. The instruction needs to be appended in the normalv-onThis is useful when the event listener is called before the event listener.
  • beforeMountCalled when the directive is first bound to an element and before the parent component is mounted.
  • mounted: called after the parent component of the bound element has been mounted.
  • beforeUpdate: called before updating the VNode containing the component.
  • pdated: in a VNode that contains componentsVnodes and their childrenCall after update.
  • beforeUnmount: called before uninstalling the parent component of the bound element
  • unmounted: is called only once when the directive is unbound from an element and the parent component is unmounted

How do we encapsulate a custom directive in Vue3.0

The first step

In the main. Js

The corresponding resume folder under SRC

import Directives from "@/Directives/index"; // const app = createApp(app); app.use(Directives); app.mount("#app");Copy the code

The second step

Js content copy is used as an example

import copy from "./copy"; Const directivesList = {copy // mount}; const directives = { install: function (app) { Object.keys(directivesList).forEach((key) => { app.directive(key, directivesList[key]); / / register}); }}; export default directives; / / throwCopy the code

The third step

Writing the contents of our instructions Vue2 and Vue3 in copy.js are just some lifecycle function modifications

import { ElMessage } from "element-plus"; // const copy = {mounted (el, {value}) {el.$value = value; el.handler = () => { if (! El. $value) {ElMessage. Warning ({message: "Hello, copied values cannot be empty." , type: "warning" }); return; } if (window.clipboardData) { window.clipboardData.setData("text", el.$value); } else { (function (content) { document.oncopy = function (e) { e.clipboardData.setData("text", content); e.preventDefault(); document.oncopy = null; }; })(el.$value); document.execCommand("Copy"); } elmessage. success(" copy succeeded "); }; // Bind the click event el.adDeventListener ("click", el.handler); }, beforeUpdate (el, { value }) { el.$value = value; }, unmounted (el) { el.removeEventListener("click", el.handler); }}; export default copy;Copy the code