Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Optimizing your App and Using Components to Display Data Chapter 3

When a component is registered, you create a custom HTML element to use in your view,


for example:


<my-component></my-component>

When naming your component, you can use kebab-case (hyphens), PascalCase (no


punctuation, but each word is capitalized) or camelCase (similar to Pascal but the first word
is not capitalized). Vue components are not restricted by, or associated with, the W3C web


components/custom element rules, but it is good practice to follow this convention of using


kebab-case.


Creating and initializing your component


Vue components are registered using the Vue.component(tagName, options) syntax.


Each component must have an associated tag name. The Vue.component registration must


happen before you initialize your Vue instance. As a minimum, each component should


have a template property—denoting what should be displayed when the component is


used. Templates must always have a single wrapping element; this is so the custom HTML


tag can be replaced with the parent container.


For example, you couldn't have the following as your template:


<div>Hello</div><div>Goodbye</div>

If you do pass a template of this format, Vue will throw an error in the browser's JavaScript
console warning you.


Create a Vue component yourself, with a simple fixed template:


Vue.component('my-component', {
template: '<div>hello</div>'
});

const app = new Vue({
el: '#app',

// App options
});

With this component declared, it would now give us a </my-


component> HTML tag to use in our view.

Free download pdf