Let’s look at the effect. This effect is the actual effect used in a real project.

What are the instructions?

As usual, here’s the official explanation:

Directives are special and v-prefixed. The value of the directive property is expected to be a single JavaScript expression (v-for is the exception, which we’ll discuss later). The directive’s job is to react to the DOM with the collateral effects of changing the value of an expression.

Again, as usual, you don’t understand, and I’ll give you an example… Ok, again I don’t know what I’m talking about, end of this article (Ctrl + F4), next.

In order to avoid the above situation, I will not explain. In fact, there are many built-in commands, such as V-if, V-for, V-bind and so on. Each instruction has its own specific function.

Custom instruction

As the name implies, it is a self-defined instruction, which can achieve the function we want. The following is to achieve a key Copy function.

The life cycle

First, take a quick look at the syntax of directives. Each directive has its own life cycle. When you look at the life cycle, you can’t help but think of hook functions.

  • bindCalled the first time the directive binds to an element. This hook is called only once. This is where you can perform one-time initialization Settings.
  • inserted: called when the bound element is inserted into the parent node (the parent node is guaranteed to exist, but not necessarily inserted into the document).
  • update: is called when the component’s VNode is updated, but may occur before its child VNodes are updated. The value of the instruction may or may not have changed.
  • componentUpdated: invoked after the VNode of the component where the directive resides and its child VNodes are all updated.
  • unbind: called only once, when directives are unbound from elements.

Take a quick look at the arguments to the hook function:

  • el: The element bound by the directive that can be used for direct operationsDOM
  • binding: an object containing the following properties:
  • name: Indicates the command namev-Prefix.
  • value: The binding value of the directive, for example:v-my-directive="1 + 1", the binding value is2.
  • oldValue: The value preceding the instruction binding, only inupdatecomponentUpdatedHooks are available. Available regardless of whether the value changes.
  • expression: Command expression in the form of a string. For example,v-my-directive="1 + 1"Where, the expression is”1 + 1“.
  • arg: Optional parameter passed to the instruction. For example,v-my-directive:foo, the parameter is”foo“.
  • modifiers: an object that contains modifiers. Such as:v-my-directive.foo.bar, the modifier object is{ foo: true, bar: true }.
  • vnode:VueVirtual nodes generated by compilation. movingVNode APITo learn more.
  • oldVnode: Indicates the last virtual nodeupdatecomponentUpdatedHooks are available.

Seems to be quite a lot, but don’t, in fact, commonly used on a few. All right, now it’s time for the show:

Wait, let’s get this straight again:

  • How docopy: Actually browsers provide native apis, but onlycopyThe selected value (that is, the mouse selected value).
  • So how do you do that in code? This uses the input control (input, textarea..). The control provides the selectedapiIs selected for the current controlvalueValue.
  • Here’s the idea:
    • Dynamically createinputThe label
    • Assign the value to be copied toinput.value
    • callapiThe selectedinput.value
    • The last callapiCopy the selected value
  1. So let’s build onejsFile (v-copy.js). Define an object. (An instruction is actually an object.)
    import { Message } from 'ant-design-vue';
    
    const vCopy = { // Take whatever name you like
      /* The bind hook function, called on the first binding, can be initialized here. El: the dom object to which it is attached value: the value passed to the instruction that we want to copy */
      bind(el, { value }) {
        el.$value = value; // Use a global property to store the value passed in, because this value is used in other hook functions
        el.handler = (a)= > {
          if(! el.$value) {// When the value is empty, give a hint, I use the ant-design-vue hint, you can do whatever you want
            Message.warning('No copy content');
            return;
          }
          // Create textarea tag dynamically
          const textarea = document.createElement('textarea');
          // Set this textarea to readonly to prevent iOS from automatically evoking the keyboard and remove the Textarea out of view
          textarea.readOnly = 'readonly';
          textarea.style.position = 'absolute';
          textarea.style.left = '-9999px';
          // Assign the copy value to the textarea tag's value property
          textarea.value = el.$value;
          // Insert the textarea into the body
          document.body.appendChild(textarea);
          // Select the value and copy it
          textarea.select();
          // textarea.setSelectionRange(0, textarea.value.length);
          const result = document.execCommand('Copy');
          if (result) {
            Message.success('Copy successful');
          }
          document.body.removeChild(textarea);
        };
        // Bind click events to copy
        el.addEventListener('click', el.handler);
      },
      // Triggered when the value passed in is updated
      componentUpdated(el, { value }) {
        el.$value = value;
      },
      // Remove event bindings when directives are unbound from elements
      unbind(el) {
        el.removeEventListener('click', el.handler); }};export default vCopy;
    Copy the code
  2. Here, one buttonCopyHow to register a custom directive globally: Create another onejsDirectives. Js) file to register all global directives.
    import copy from './v-copy';
    // Custom instruction
    const directives = {
      copy,
    };
    // This method can be used to batch register instructions
    export default {
      install(Vue) {
        Object.keys(directives).forEach((key) = >{ Vue.directive(key, directives[key]); }); }};Copy the code
  3. Finally, in themain.jsIs introduced like this:
    import Vue from 'vue';
    import Directives from './directives';
    
    Vue.use(Directives);
    Copy the code
  4. Finally,, how to use it.
    <template>
      <button v-copy="copyText">copy</button>
    </template>
    
    <script>
    export default {
      data() {
        return {
          copyText: 'Contents to Copy'}; }};</script>
    Copy the code

OK, we’re done. Scatter the flowers.