Build Components - sikaeducation/vue-curriculum GitHub Wiki
A component needs 3 things:
- Name
- File
- Registration
Vue component names follow a set of rules:
To ensure compatibility with the web component spec, your component name should be at least two words.
There are no circumstances where snake_case or camelCase are appropriate for components.
Within a script, components should always be written in PascalCase, like this:
import SomeComponent from "./SomeComponent"
export default {
components: {
SomeComponent,
},
}
PascalCase is more common due to ease of code completion and because it mirrors the variable usage, but either are acceptable:
SomeComponent.vue
some-component.vue
If you're using Vue CLI or webpack, use PascalCase in your templates:
<SomeComponent />
If you're not using a build tool, you'll need to use kebab-case:
<some-component />
Write out the entire word, every time.
Instead of TextFormInput
, name it FormInputText
. This helps with alphabetization in file directories.
-
App
- Indicates that there should only be one instance of something in the app, such asAppHeader
andAppSidebar
-
Base
- Indicates that something is providing some base functionality or styling and intended to be extended, such asBaseInput
andBaseButton
There are no rules about where files must go, but it's common to separate them into a views
and components
folder. There is no technical difference between these, but semantically a view is something that is routed directly to, and a component is anything else. You can nest folders inside of these as needed.
In a Vue CLI app, components are registered within a router or directly within the component hierarchy:
<script>
import SomeComponent from "./SomeComponent"
import SomeOtherComponent from "./SomeComponent"
export default {
name: "App",
components: {
SomeComponent,
SomeOtherComponent,
},
}
</script>
In an app without a build process, components are registered globally:
const SomeComponent = {
template: "<p>Hi!</p>",
}
const SomeOtherComponent = {
template: "<p>Yo!</p>",
}
const App = {
template: "<div><some-component /><some-other-component /></div>", // Will look up the registration on render
}
const app = Vue.createApp(App) // Bootstraps the app
app.component('some-component', SomeComponent) // Registers the component
app.component('some-other-component', SomeOtherComponent) // Registers the component
app.mount('#app') // Renders the app inside of a DOM element with the ID "app"
Which of these are valid component names?
<CartItem />
<Item />
tab.vue
<cart-item-heading />
<cartItemDisabled />
<AppSidebar />
import BlogPost from "BlogPost";
<StarRating />
user-addr.vue
<comments />