javascript 在Vue.js中全局注册组件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 在Vue.js中全局注册组件相关的知识,希望对你有一定的参考价值。

In main.js File add:

import BaseIcon from '@/components/BaseIcon.vue'
Vue.component('BaseIcon', BaseIcon) //To Register it globally

//No need to register the component in other components

//If more than 3 components need to be added, add the following code to the main.js file:
//Make sure Lodash Dependency is installed
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
  // The relative path of the components folder
  './components',
  // Whether or not to look in subfolders
  false,
  // The regular expression used to match base component filenames
  /Base[A-Z]\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
  // Get component config
  const componentConfig = requireComponent(fileName)

  // Get PascalCase name of component
  const componentName = upperFirst(
    camelCase(
      // Strip the leading `./` and extension from the filename
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
    )
  )

  // Register component globally
  Vue.component(
    componentName,
    // Look for the component options on `.default`, which will
    // exist if the component was exported with `export default`,
    // otherwise fall back to module's root.
    componentConfig.default || componentConfig
  )
})

以上是关于javascript 在Vue.js中全局注册组件的主要内容,如果未能解决你的问题,请参考以下文章

vue js 可以全局注册所有组件吗?

vue.js注册引用全局消息组件

Vue.js之组件嵌套

如何使用 vue-router 注册全局组件

vue.js基础知识篇:组件详解

vue.js组件(component)