Home> Web Front-end> Vue.js> body text

See how to encapsulate an automated registration global component in Vue

青灯夜游
Release: 2021-11-18 19:37:00
forward
2098 people have browsed it

In this article, let’s take a look at how to encapsulate an automated registration global component in Vue. I hope it will be helpful to everyone!

See how to encapsulate an automated registration global component in Vue

During the project development process, we often encapsulate some commonly used global components. However, every time you add a component, you need to manually introduce registration in main.js, which is not only troublesome but also requires a lot of code, which is really annoying. So simply encapsulate an automated registration global component. [Related recommendations: "vue.js Tutorial"]

1. Customize the global component folder

Create a new one under srcglobalComponents, used to store global components and create a new component, such asOrange;

See how to encapsulate an automated registration global component in Vue

2. Component automatic registration configuration File

Create an index.js inglobalComponentsto find all components and automatically register

// 自动注册全局组件,每次新增组件必须重新编译 import Vue from 'vue' const requireComponent = require.context( '../globalComponents', // 其组件目录的相对路径 true, // 是否查询其子目录 /\.vue$/ // 匹配基础组件文件名的正则表达式 ) requireComponent.keys().forEach(fileName => { const componentConfig = requireComponent(fileName); // 获取组件配置 /** * 兼容 import export 和 require module.export 两种规范 */ // 如果这个组件选项是通过 export default 导出的,就会优先使用 .default const comp = componentConfig.default || componentConfig; Vue.component(comp.name, comp) // 此处的name是组件属性定义的name })
Copy after login

3. Edit Orange/index. vue

The most important thing about the component is the name defined by the component attribute (name is the automatically registered component name)

 
Copy after login

4. Import globalComponents/ into the entry file main.js index.js

// main.js import Vue from 'vue' // 自动注册全局组件 import './globalComponents/index.js'
Copy after login
  • After basically completing the above steps, you are done. You can then use this global component directly~
  • Usage method:
Copy after login

For more programming-related knowledge, please visit:Introduction to Programming! !

The above is the detailed content of See how to encapsulate an automated registration global component in Vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
vue
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn