Close read Vue official documentation series 🎉

The component named

There are two ways to name components:

  • Kebab-case: short line separated names (kebab style), all lowercase letters, words linked by a “hyphen”.
  • PascalCase: The large hump in camelCase, capitalized.

As a best practice, PascalCase nomenclature is recommended for component filename and component name (component name option). The custom component elements introduced in the Vue template are named kebab-case.

Mycomponent. vue # Component files are named PascalCaseCopy the code
export default {
    name:'MyCompoent' // The component name is PascalCase
}
Copy the code
<! -- Use kebab-case when introducing custom elements in the template -->
<my-component></my-component>
Copy the code

Vue also supports custom elements named PascalCase in templates (string templates, indirect DOM).

<MyComponent></MyComponent>
Copy the code

Why do we strongly recommend kebab-case naming of custom elements? There are two main reasons:

  • From the perspective of the browser, the browser is case-insensitive, as normal HTML tags, if there are uppercase letters in the browser will be converted to lowercase.
  • On the specification side, the W3C specification requires adoptionkebab-caseAs the tag name of the custom component.

The component registration

Global registration

Vue.component('my-component'{});Copy the code

Automated global registration

Take advantage of webpack’s require.context() feature.

const upperFirst from 'lodash/upperFirst';
const camelCase from 'lodash/camelCase';
const components = require.context('./components'.false./My[A-Z]\w+\.(vue|js)$/);
const componentName = [];

components.keys().forEach(fileName= > {
    const componentModule = components[fileName];
    const componentName = upperFirst(camelCase(fileName('/').pop().replace(/\.\w+$/.' ')));
    // Batch register global componentsVue.com ponent (the componentName, componentModule. Default | | componentModule)});Copy the code

This approach is more commonly used for registering UI component libraries.

Local registration

Specify this in the components option of the component optionsAPI.

{
    components: {'my-component-a':MyComponentA,
        MyCompnentB
    }
}
Copy the code

A locally registered component is only valid for the current component, and a locally registered component cannot be inherited.

If you use a build tool such as Webpack, you can also do modular local registrations.

import ComponentA from './ComponentA'
import ComponentC from './ComponentC'

export default {
  components: {
    ComponentA,
    ComponentC
  },
  // ...
}
Copy the code