SoFunction
Updated on 2025-04-06

Detailed explanation of application examples of reusability in vue3 component development

Reusability is also an advantage of component development, which can make the code more concise and elegant and convenient to maintain. The following mainly describes some API applications in vue3 that can reflect reusability.

Custom commands

instruction(Directives) is withv-Special attribute of prefix.

v-text v-show v-if... etc are some built-in instructions in vue. When these built-in instructions cannot meet our requirements, they can also be used at this time.Custom commands

Basic structure

const app = ({})
// Register a global custom command('loading', {
  mounted(el, binding) {},
  updated(el, binding) {},
  // ...
})

A custom directive object can provide the followingHook function

  • created: Called before the attribute or event listener of the binding element is applied. Instructions need to be attached to normalv-onThis is useful when in the event listener before the event listener is called.
  • beforeMount: When the directive is bound to an element for the first time and is called before mounting the parent component.
  • mounted: Called after the parent component of the binding element is mounted.
  • beforeUpdate: Called before updating the VNode containing the component.
  • updated: In VNode containing componentsVNode of its subcomponentsCalled after update.
  • beforeUnmount: Called before uninstalling the parent component of the binding element
  • unmounted: Only call once when the directive is unbound from the element and the parent component has been uninstalled.

Some parameters of the hook function

Contains two parameterselandbindingelThe element bound to the directive. This can be used to manipulate the DOM directly.bindingContains the following objects:

  • instance: A component instance that uses a directive.
  • value: The value passed to the instruction. For example, inv-my-directive="1 + 1"In, the value is2
  • oldValue: The previous value, only inbeforeUpdateandupdatedAvailable in  . Available regardless of whether the value has changed or not.
  • arg: Parameters passed to the instruction (if any). For example,v-my-directive:fooIn  , arg is"foo"
  • modifiers: Object containing modifiers (if any). For example,In  , the modifier object is{foo: true,bar: true}
  • dir: An object passed as a parameter when registering an instruction.

Dynamic command pass parameters

v-mydir:[t]="val" //T parameter passed

tThe value can be passed through the parameters of the hook functionObtained,valThe value ofObtained.

Custom v-loading directives

Write one firstComponent, content is the style in loading.

<template>
  <div class="k_loading_mask">
    <div class="loading-icon">
      <svg viewBox="0 0 1024 1024" xmlns="http:///2000/svg">
        <path fill="currentColor"
          d="M512 64a32 32 0 0 1 32 32v192a32 32 0 0 1-64 0V96a32 32 0 0 1 32-32zm0 640a32 32 0 0 1 32 32v192a32 32 0 1 1-64 0V736a32 32 0 0 1 32-32zm448-192a32 32 0 0 1-32 32H736a32 32 0 1 1 0-64h192a32 32 0 0 1 32 32zm-640 0a32 32 0 0 1-32 32H96a32 32 0 0 1 0-64h192a32 32 0 0 1 32 32zM195.2 195.2a32 32 0 0 1 45.248 0L376.32 331.008a32 32 0 0 1-45.248 45.248L195.2 240.448a32 32 0 0 1 0-45.248zm452.544 452.544a32 32 0 0 1 45.248 0L828.8 783.552a32 32 0 0 1-45.248 45.248L647.744 692.992a32 32 0 0 1 0-45.248zM828.8 195.264a32 32 0 0 1 0 45.184L692.992 376.32a32 32 0 0 1-45.248-45.248l135.808-135.808a32 32 0 0 1 45.248 0zm-452.544 452.48a32 32 0 0 1 0 45.248L240.448 828.8a32 32 0 0 1-45.248-45.248l135.808-135.808a32 32 0 0 1 45.248 0z">
        </path>
      </svg>
    </div>
    <div class="tips">{{ tips }}</div>
  </div>
</template>
<script setup>
import { ref } from 'vue';

const tips = ref("loading");
</script>
<style lang="scss">
.loading-icon {
  width: 30px;
  height: 30px;
  color: #fff;

  svg {
    animation: rotating 2s linear infinite;
    display: inline-block;
    width: 100%;
    height: 100%;
  }
}

.k_loading_mask {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .6);
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1000;
}

.tips {
  color: #fff;
}
</style>

Create a js filesrc/directives/, export the object of the custom directive:

export default {
	mounted(el, binding) {
		// Insert element		const app = createApp(LoadingIcon);
		const instance = (("div"));
		 = instance;
		(.$el);

		 = "relative";
	},
	updated(el, binding) {

	},
};

Dynamically set the prompt text according to the parameters sent by the user to the command:

mounted(el, binding){
// ...
	// Prompt text	if () {
		 = ;
	}
}

When the value of the command binding changes, set to show or hide loading:

	updated(el, binding) {
		if (!) {
			(.$el);
		} else {
			(.$el);
		}
	},

Global registrationCustom directives:

const app = createApp(App);

import loading from "./directives/";
("loading",loading);

usev-loadinginstruction:

<template>
        <div v-loading="showLoading" class="loading-box"></div>
        <div v-loading:[tipsLoading]="showLoading" class="loading-box2">
          Some content...
        </div>
</template>

<script setup>
const showLoading = ref(true);
const tipsLoading = ref("Please wait");
const close = () => {
   = !;
}
</script>

Plugin

Plugins are self-contained code that usually adds global-level functionality to Vue. It can be publicinstall()Methodobject, it can also befunction

Whenever the plugin is added to the application, if it is an object, it will be calledinstallmethod. If it is afunction, the function itself will be called. In both cases, it will receive two parameters: by Vue'screateAppGeneratedappOptions passed in by objects and users.

Basic structure

Export an object containinginstallmethod.

export default {
  install: (app, options) => {
    // ...
  }
}

Using plug-ins

In usecreateApp()After initializing the Vue application, call ituse()Methods to add plugins to the application.

const app = createApp(App);

(plugin);

Implement a global state management plug-in

In small projects, usevuexGlobal state management tools can easily make the code redundant and complicated. If global state management is still needed, you can implement a mini version of global state management by yourself through plug-ins.

New

import { reactive } from 'vue';

const state = reactive({
  str: 'String',
});

const minstore = {
  state,
};

export default {
  install: (app) => {
    ('minstore', minstore);
  },
};

Install this plugin:

import minstore from './minstore/';

const app = createApp(App);
(minstore).mount('#app');

Used in componentsminstore

const minstore = inject('minstore');
();
<p>{{  }}</p>

Teleport Transmission

Let’s take a look at a case first:

        &lt;div style="position: relative;"&gt;
          &lt;div class="model" style="position:absolute"&gt;Modal Box&lt;/div&gt;
        &lt;/div&gt;

The positioning of the inner modal box is relative to the parent, if you want it to be relative tobodyIf you position the global pop-up modal box, it may be troublesome to implement.

Teleport provides a clean way to allow us to control which parent node in the DOM renders HTML.

use<teleport>andtoAttributes, let Vue "replace this HTMLSendarrivebodyUnder the tag.

        &lt;div style="position: relative;"&gt;
          &lt;teleport to='body'&gt;
            &lt;div v-show="showModel" class="model" style="position:absolute"&gt;Modal Box&lt;/div&gt;
          &lt;/teleport&gt;
        &lt;/div&gt;

At this point, HTML is inserted intobodyUnder the label, the positioning of the modal box is relative tobodyLabel.

Related links

Common APIs for component development of vue3

Code demo address/kongcodes/v…

Starting from 0 vue3 project construction

Summarize

This is the article about reusable application in vue3 component development. For more related content of vue3 reusable application, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!