Глобальная регистрация компонентов в Vuejs в подпапках - PullRequest
0 голосов
/ 08 декабря 2018

Я ознакомился с документацией на веб-сайте Vuejs, чтобы узнать, как зарегистрировать компоненты vue в глобальном масштабе.

Я определил, что относительный путь к папке компонентов равен ./global, и для поиска в подпапке установлен true (по умолчанию false).Тем не менее, он все еще не смотрит на подпапки.

Я также console.logged ключами компонентов, чтобы видеть, включены ли какие-либо vue компоненты, но он только возвратил компоненты в глобальной (корневой) папке.

https://vuejs.org/v2/guide/components-registration.html

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

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

console.log(requireComponent.keys())

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
  )
})

1 Ответ

0 голосов
/ 08 декабря 2018

Вот что я написал для достижения того же результата:

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

requireComponent.keys().forEach(fileName => {
  // Get component config
  const componentConfig = requireComponent(fileName)
  // Get PascalCase name of component
  const componentName = Vue._.upperFirst(
    Vue._.camelCase(
      fileName
        .split('/')
        .pop()
        .replace(/\.\w+$/, '')
    )
  )

  // 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
  )
})

Убедитесь, что все ваши файлы в глобальном формате имеют заглавные буквы и имеют расширение .vue или .js.

Кроме того, указав путь, который вы указали, убедитесь, что main.js (или как называется ваш файл начальной загрузки) находится на один каталог выше глобальных.Пример:

/ src main.js / global

Это сделает файл, такой как ProgressBar.vue, глобально доступным во всех ваших компонентах как ProgressBar

<ProgressBar></ProgressBar>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...