What is a custom directive?

Built-in directives such as v-model, V-show, V-bind, V-ON, etc. Developers can also define their own directives. Vue custom directives can be created in two ways: global registration and component registration

Global registration

  1. New directives/index.js file under SRC
import wht from "./wht";
import debounce from "./debounce";
import copy from "./copy";
const directives = {
  debounce,
  wht,
  copy,
};

export default {
  install(Vue) {
    Object.keys(directives).forEach((item) = >{ Vue.directive(item, directives[item]); }); }};Copy the code
  1. The main js references
import Vue from "vue";
import App from "./App";
import router from "./router";
// Here is the cache reference begin
import Directives from "./directives";

Vue.use(Directives);
// Here is the cache reference end

Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
  el: "#app",
  router,
  components: { App },
  template: "<App/>"});Copy the code
  1. Create instruction
  const copy = {
  /** * initializes the binding only once, when the directive is first bound to the element. You can define an initialization action * that is performed once at binding time@param {*} El The current element *@param {*} For example, v-copy=" test text "{value} is short for binding.value
  bind: function(el, { value }) {
    el.newvalue = value;
    el.handler = function() {
      console.log(value);
      if(! el.newvalue) {console.log("Copied value is null");
        return;
      }
      let textarea = document.createElement("textarea");
      textarea.style.position = "absolute";
      textarea.style.left = "-1000px";
      textarea.style.readOnly = "readonly";
      textarea.value = el.newvalue;
      document.body.appendChild(textarea);
      textarea.select();

      let result = document.execCommand("copy");
      if (result) {
        console.log("Copy successful");
      }
      document.body.removeChild(textarea);
    };
    el.addEventListener("click", el.handler);
  },
  // called when the bound element is inserted into the parent node.
  inserted: function() {
    // Insert the node
  },
  /** * called when the template to which the bound element belongs has completed an update cycle. *@param {*} El Current element *@param {*} Gets the value */ for the current binding
  componentUpdated: function(el, { value }) {
    el.newvalue = value;
  },
  // Only called once, when the instruction is unbound from the element.
  unbind: function(el, { value }) {
    el.removeEventListener("click", el.handler); }};export default copy;


Copy the code
  1. usage
<template> <div class=""> <input type="text" V-model ="copyText" placeholder=" please input the text" /> <button V-copy ="copyText"> </button> </div> </template> <script> export default {data() {return {copyText: 'Contents of instruction to copy ',}},} </script>Copy the code

Quote 1: juejin.cn/post/690602…

Quote 2: juejin.cn/post/684490…