There are many UE-BASED UI component libraries, such as iView, Element-UI, etc. But sometimes these libraries don’t meet our development needs, and we need to write our own plug-in.

Take the first chestnut

After setting up the project directory with vue-CLI, create a new folder under SRC/Components to put the plug-in we want to write, as shown in the picture below:

Write our component in index.vue as follows:

Vue.component is used to register components with Vue.component.

Next we need to import the index.js file we just wrote in the default main.js file and use it with vue. use as follows:

Now you can use it directly in app.vue. You can see that the corresponding components are displayed on the page, as shown in the figure below:

We can also customize the click event and pass it as a parameter to our plugin. The plugin can get the event using the props property, as shown in the figure below:

You can see that the page is in effect:

Vue.component(ID, [definition]) is used to register or obtain components.

Vue.use(plugin) Is used to install vue.js plug-in. If the plug-in is an object, the install method must be provided. If the plug-in were a function, it would be used as the install method. When the install method is called, Vue is passed in as an argument. When the install method is called multiple times by the same plug-in, the plug-in will only be installed once.

Take the second chestnut

Let’s create another folder, as shown below:

We need to write a component that displays incoming content and automatically disappears after 3 seconds. The code looks like this:

Next we’ll create it using the constructor in index.js, as shown in the figure below:

Reference the js file from the default main.js file and add it to the Vue instance, so we can call it directly from this.$seconddemo(), as follows:

import SecondDemo from './components/global/seconddemo/index'
Vue.prototype.$seconddemo = SecondDemo
Copy the code

When you use it in app.vue, the plugin loads successfully, as shown in the following figure:

Vue.extend(options) is the constructor of Vue and is used to create a “subclass”.

Manage custom components in a unified manner

When the number of components is large, we can manage these custom components by providing a unified export file. First, create an index.js file in the Global folder, as shown in the following figure:

The index.js file helps us register all our custom components with Vue.com Ponent, and finally export an object containing the install method to vue.use ().

We don’t need to add dynamic components one by one in main.js, just import the uniform index.js file and use vue.use.

import global from './components/global/index.js'
Vue.use(global)
Copy the code