banner



How To Register A Component Vue

You're browsing the documentation for v2.x and before. For v3.x, click here.

Component Registration

This folio assumes you've already read the Components Basics. Read that first if y'all are new to components.

Component Names

When registering a component, information technology will ever be given a name. For example, in the global registration we've seen and so far:

          Vue.component('my-component-proper noun', {            /* ... */            })        

The component'southward name is the showtime argument of Vue.component.

The proper name y'all requite a component may depend on where you intend to employ information technology. When using a component directly in the DOM (as opposed to in a string template or unmarried-file component), we strongly recommend following the W3C rules for custom tag names (all-lowercase, must contain a hyphen). This helps you avoid conflicts with current and future HTML elements.

You can see other recommendations for component names in the Style Guide.

Name Casing

You lot accept two options when defining component names:

With kebab-case

          Vue.component('my-component-name', {            /* ... */            })        

When defining a component with kebab-case, you lot must also employ kebab-instance when referencing its custom element, such as in <my-component-name>.

With PascalCase

          Vue.component('MyComponentName', {            /* ... */            })        

When defining a component with PascalCase, you tin use either case when referencing its custom chemical element. That means both <my-component-proper name> and <MyComponentName> are acceptable. Note, however, that simply kebab-instance names are valid straight in the DOM (i.e. non-cord templates).

Global Registration

Then far, we've only created components using Vue.component:

          Vue.component('my-component-name', {            // ... options ...            })        

These components are globally registered. That means they can exist used in the template of whatsoever root Vue case (new Vue) created after registration. For example:

          Vue.component('component-a', {            /* ... */            }) Vue.component('component-b', {            /* ... */            }) Vue.component('component-c', {            /* ... */            })            new            Vue({            el:            '#app'            })        
                      <div              id="app">            <component-a>            </component-a>            <component-b>            </component-b>            <component-c>            </component-c>            </div>                  

This even applies to all subcomponents, meaning all three of these components will likewise be available within each other.

Local Registration

Global registration frequently isn't ideal. For example, if you're using a build system like Webpack, globally registering all components ways that even if you lot stop using a component, it could still be included in your terminal build. This unnecessarily increases the corporeality of JavaScript your users have to download.

In these cases, you tin can define your components as plain JavaScript objects:

                      var            ComponentA = {            /* ... */            }            var            ComponentB = {            /* ... */            }            var            ComponentC = {            /* ... */            }        

And so ascertain the components y'all'd like to use in a components pick:

                      new            Vue({            el:            '#app',            components: {            'component-a': ComponentA,            'component-b': ComponentB   } })        

For each property in the components object, the key will exist the name of the custom element, while the value will contain the options object for the component.

Note that locally registered components are not as well bachelor in subcomponents. For case, if you lot wanted ComponentA to exist available in ComponentB, you lot'd accept to use:

                      var            ComponentA = {            /* ... */            }            var            ComponentB = {            components: {            'component-a': ComponentA   },            // ...            }        

Or if y'all're using ES2015 modules, such as through Babel and Webpack, that might look more like:

                      import            ComponentA            from            './ComponentA.vue'            export            default            {            components: {     ComponentA   },            // ...            }        

Note that in ES2015+, placing a variable proper noun like ComponentA within an object is shorthand for ComponentA: ComponentA, meaning the name of the variable is both:

  • the custom element name to use in the template, and
  • the name of the variable containing the component options

Module Systems

If yous're non using a module system with import/require, you tin can probably skip this department for at present. If you are, we have some special instructions and tips merely for you.

Local Registration in a Module System

If you lot're all the same here, and so it's likely you're using a module system, such equally with Babel and Webpack. In these cases, we recommend creating a components directory, with each component in its own file.

So you'll need to import each component you'd like to employ, before y'all locally register it. For example, in a hypothetical ComponentB.js or ComponentB.vue file:

                      import            ComponentA            from            './ComponentA'            import            ComponentC            from            './ComponentC'            export            default            {            components: {     ComponentA,     ComponentC   },            // ...            }        

Now both ComponentA and ComponentC tin be used inside ComponentB'southward template.

Automatic Global Registration of Base Components

Many of your components will be relatively generic, peradventure but wrapping an element like an input or a button. We sometimes refer to these as base of operations components and they tend to be used very oftentimes beyond your components.

The result is that many components may include long lists of base of operations components:

                      import            BaseButton            from            './BaseButton.vue'            import            BaseIcon            from            './BaseIcon.vue'            import            BaseInput            from            './BaseInput.vue'            export            default            {            components: {     BaseButton,     BaseIcon,     BaseInput   } }        

Just to support relatively footling markup in a template:

                      <BaseInput              v-model="searchText"              @keydown.enter="search"              />            <BaseButton              @click="search">            <BaseIcon              name="search"/>            </BaseButton>                  

Fortunately, if you're using Webpack (or Vue CLI 3+, which uses Webpack internally), you tin can utilise crave.context to globally annals only these very common base of operations components. Hither's an case of the code you might use to globally import base components in your app's entry file (due east.one thousand. src/main.js):

                      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            './components',            // Whether or not to await in subfolders            false,            // The regular expression used to friction match base of operations component filenames            /Base[A-Z]\westward+\.(vue|js)$/ )  requireComponent.keys().forEach(              fileName              =>            {            // Get component config            const            componentConfig = requireComponent(fileName)            // Get PascalCase name of component            const            componentName = upperFirst(     camelCase(            // Gets the file name regardless of folder depth            fileName         .split('/')         .pop()         .supercede(/\.\west+$/,            '')     )   )            // Register component globally            Vue.component(     componentName,            // Look for the component options on `.default`, which volition            // exist if the component was exported with `consign default`,            // otherwise fall back to module's root.            componentConfig.default || componentConfig   ) })        

Remember that global registration must have place before the root Vue example is created (with new Vue). Here's an example of this design in a real project context.

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

Posted by: hilldiespithe.blogspot.com

0 Response to "How To Register A Component Vue"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel