There are three ways to register vue custom components: 1. Partial registration, register the custom component in the components of the App. 2. Global registration, register (mount) custom components in "main.js". 3. Create a folder with the same name as the component in the "src/plugin" directory, then place the custom component file in this directory, and then create another "index.js" file in this directory. Write the registration code in the file to register the custom component as a plug-in.
The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.
Create project
Execute the following example command through cmd to initialize our Vue project
vue create helloworld cd helloworld code . npm run serve
After the command is executed, the project structure is as shown below :
Next, we create a custom component splash.vue
in the src/components
directory. The sample code is as follows Shown:
<template> <div> <p>{{ title }}</p> <p>{{ message }}</p> </div> </template> <script> export default { name: "splash", props:['title'], data: function () { return { message: "组件启动中...", }; }, }; </script>
Registered as a local component
We know that vue will automatically create a project for us through Vue-CLI
The root component of App.vue
is used to host the entire application. If we register our custom component in App's components
, then it is also considered a local component and can only be applied Within a component like App. The registration method is as follows:
<template> <div id="app"> <img src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="Vue logo" /> <!-- 3.应用自定义组件 --> <splash title="hello world"></splash> </div> </template> <script> // 1.导入组件 import Splash from "./components/Splash.vue"; export default { name: "App", components: { // 2.注册局部组件 Splash, }, }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
Execute npm run serve
, and the following effect will appear:
Register as a global component
If we want to register our component as a global component so that all other components can use it, we need to register our component as a global component. Similarly, we need to register our global component in 'main.js', the sample code is as follows:
import Vue from 'vue' import App from './App.vue' // 1. 导入自定义组件 import Splash from './components/Splash.vue' Vue.config.productionTip = false // 2. 将自定义组件注册成全局组件 Vue.component(Splash.name, Splash) new Vue({ render: h => h(App), }).$mount('#app')
ModifyHelloWorld.vue
, use the global component registered above, The sample code is as follows:
<template> <div class="hello"> <h1 id="nbsp-msg-nbsp">{{ msg }}</h1> <!-- 应用自定义组件 --> <splash></splash> </div> </template> <script> export default { name: "HelloWorld", props: { msg: String, }, }; </script> <style scoped> .hello { border: 1px dashed #00f; } </style>
Modify App.vue
and use the global component registered above. The sample code is as follows:
<template> <div id="app"> <img src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="Vue logo" /> <splash></splash> <hello-world msg="我是子组件"></hello-world> </div> </template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { name: "App", components: { HelloWorld, }, }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
Execute npm run serve
, the following effect will appear:
Register as plug-in
Because plug-ins are more flexible , so we can register custom components as global components. According to Vue's convention, we need to adjust our project structure.
Create a folder with the same name as the component in the src/plugin
directory, then put the splash.vue file we defined above into this directory, and then create it under this directory A index.js
file, by writing the registration code in this file, register our custom component as a plug-in. The sample code is as follows:
import Splash from './Splash' export default { install: function (Vue, options) { // 1.获取构造函数 const contructor = Vue.extend(Splash) // 2. 实例化组件对象 const instance = new contructor() // 3. 创建页面元素 const oDiv = document.createElement('div') document.body.appendChild(oDiv) // 4. 将组件挂载到页面元素上 instance.$mount(oDiv) if (options !== null && options.title !== undefined) { instance.title = options.title } // 添加全局方法 Vue.ToggleSplash = function () { instance.isShow = !instance.isShow; } // 添加实例方法 Vue.prototype.$ToggleSplash = function () { instance.isShow = !instance.isShow; } } }
Modify main.js
, the sample code is as follows:
import Vue from 'vue' import App from './App.vue' // 1. 导入自定义组件 import Splash from './plugin/splash/index' Vue.config.productionTip = false // 2. 将自定义组件注册成组件 Vue.use(Splash, { title: 'hello world' }) new Vue({ render: h => h(App), }).$mount('#app')
Next, we can call Vue in any component The global method or instance method of the object is used to control our custom components. For example, we can use it in hello-world
like this:
<template> <div class="hello"> <h1 id="nbsp-msg-nbsp">{{ msg }}</h1> <button @click="toggle1">使用全局方法控制显示或隐藏插件</button> <button @click="toggle2">使用实例方法控制显示或隐藏插件</button> </div> </template> <script> import Vue from "vue"; export default { name: "HelloWorld", props: { msg: String, }, methods: { toggle1: function () { // 通过全局方法来访问自定义组件 Vue.ToggleSplash(); }, toggle2: function () { // 通过实例方法来访问自定义组件 this.$ToggleSplash(); }, }, }; </script> <style scoped> .hello { border: 1px dashed #00f; } </style>
Execute npm run serve
, The following effect will appear:
[Related recommendations: vuejs video tutorial, web front-end development]
The above is the detailed content of There are several ways to register vue custom components.. For more information, please follow other related articles on the PHP Chinese website!

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.