Home > Article > Web Front-end > See how to encapsulate an automated registration global component in Vue
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!
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 as Orange;
2. Component automatic registration configuration File
Create an index.js in globalComponents to 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 })
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)
<template> <div class="wrapper"> Orange </div> </template> <script> export default { name: 'Orange', // 此处的name属性值将为后面使用的组件名 <orange />,需唯一 components: {}, props: {}, data() { return {} }, created() {}, mounted() {}, methods: {} } </script>
4. Import globalComponents/ into the entry file main.js index.js
// main.js import Vue from 'vue' // 自动注册全局组件 import './globalComponents/index.js'
<template> <div class="wrapper"> <!-- 自动注册的全局组件 --> <orange /> </div> </template>
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!