Home >Web Front-end >Vue.js >See how to encapsulate an automated registration global component in Vue

See how to encapsulate an automated registration global component in Vue

青灯夜游
青灯夜游forward
2021-11-18 19:37:002179browse

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 as Orange;

See how to encapsulate an automated registration global component in Vue

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: &#39;Orange&#39;, // 此处的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 &#39;vue&#39;
// 自动注册全局组件
import &#39;./globalComponents/index.js&#39;
  • After basically completing the above steps, you are done. You can then use this global component directly~
  • Usage method:
<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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete