How To Register Vue Components
Creating our first Vue component
Now it's time to dive deeper into Vue, and create our own custom component — we'll start by creating a component to correspond each item in the todo list. Along the way, nosotros'll learn near a few important concepts such equally calling components inside other components, passing data to them via props, and saving information country.
Creating a ToDoItem component
Let'southward create our first component, which will brandish a unmarried todo item. We'll use this to build our list of todos.
- In your
moz-todo-vue/src/componentsdirectory, create a new file namedToDoItem.vue. Open the file in your lawmaking editor. - Create the component'due south template section past adding
<template></template>to the acme of the file. - Create a
<script></script>department below your template section. Inside the<script>tags, add together a default exported objectexport default {}, which is your component object.
Your file should now look like this:
<template > </template > <script > export default { } ; </script > We can now brainstorm to add bodily content to our ToDoItem. Vue templates are currently but allowed a unmarried root element — one element needs to wrap everything inside the template section (this will modify when Vue 3 comes out). We'll use a <div> for that root element.
- Add an empty
<div>inside your component template at present. - Inside that
<div>, let's add a checkbox and a corresponding label. Add anidto the checkbox, and aforattribute mapping the checkbox to the label, as shown below.<template > <div > <input type = "checkbox" id = "todo-item" /> <label for = "todo-detail" > My Todo Particular </label > </div > </template >
Using TodoItem within our app
This is all fine, but nosotros haven't added the component to our app all the same, so there'south no style to test information technology and run into if everything is working. Let's add together information technology now.
- Open upwardly
App.vueonce more. - At the elevation of your
<script>tag, add the following to import yourToDoItemcomponent:import ToDoItem from './components/ToDoItem.vue' ; - Inside your component object, add the
componentsholding, and inside it add yourToDoItemcomponent to annals it.
Your <script> contents should now await like this:
import ToDoItem from './components/ToDoItem.vue' ; export default { proper noun : 'app' , components : { ToDoItem } } ; This is the same fashion that the HelloWorld component was registered past the Vue CLI before.
To really render the ToDoItem component in the app, you need to get upwardly into your <template> element and call it as a <to-do-item></to-do-item> element. Note that the component file name and its representation in JavaScript is always in PascalCase (e.1000. ToDoList), and the equivalent custom element is always in kebab-case (east.g. <to-do-list>).
- Underneath the
<h1>, create an unordered list (<ul>) containing a single listing detail (<li>). - Inside the list item add
<to-practise-item></to-practice-item>.
Your App.vue <template> contents should now look something like this:
<div id = "app" > <h1 > To-Do List </h1 > <ul > <li > <to-do-item > </to-do-particular > </li > </ul > </div > If you check your rendered app again, you should at present see your rendered ToDoItem, consisting of a checkbox and a label.
Making components dynamic with props
Our ToDoItem component is still not very useful considering we can only really include this once on a folio (IDs demand to be unique), and we have no mode to ready the label text. Naught about this is dynamic.
What we need is some component state. This can be achieved by adding props to our component. You tin recall of props as being similar to inputs in a function. The value of a prop gives components an initial land that affects their brandish.
Registering props
In Vue, in that location are two means to register props:
- The first way is to just list props out as an array of strings. Each entry in the assortment corresponds to the name of a prop.
- The 2d way is to define props as an object, with each key respective to the prop proper noun. Listing props as an object allows you to specify default values, marker props as required, perform basic object typing (specifically around JavaScript primitive types), and perform simple prop validation.
Note: Prop validation only happens in development manner, so you can't strictly rely on it in product. Additionally, prop validation functions are invoked before the component instance is created, so they do not have access to the component land (or other props).
For this component, we'll use the object registration method.
- Go back to your
ToDoItem.vuefile. - Add together a
propsbelongings inside the exportdefault {}object, which contains an empty object. - Within this object, add ii properties with the keys
labelanddone. - The
labelkey'southward value should be an object with two properties (or props, as they are called in the context of existence available to the components).- The first is a
requiredproperty, which will have a value oftrue. This volition tell Vue that we wait every case of this component to accept a label field. Vue will warn united states of america if aToDoItemcomponent does not have a label field. - The second property we'll add together is a
blazonproperty. Set the value for this property as the JavaScriptStringblazon (note the capital "S"). This tells Vue that we wait the value of this property to exist a cord.
- The first is a
- Now on to the
doneprop.- Outset add together a
defaultfield, with a value offalse. This means that when nodoneprop is passed to aToDoItemcomponent, thewashedprop will have a value of false (bear in mind that this is non required — nosotros simply needdefaulton not-required props). - Next add a
blazonfield with a value ofBoolean. This tells Vue nosotros expect the value prop to be a JavaScript boolean type.
- Outset add together a
Your component object should now look like this:
<script> export default { props : { label : { required : truthful , type : String } , washed : { default : false , blazon : Boolean } } } ; < /script> Using registered props
With these props defined inside the component object, nosotros can at present use these variable values inside our template. Let's start past adding the label prop to the component template.
In your <template>, replace the contents of the <label> element with {{label}}.
{{}} is a special template syntax in Vue, which lets us print the result of JavaScript expressions defined in our class, inside our template, including values and methods. It's important to know that content inside {{}} is displayed as text and not HTML. In this instance, we're printing the value of the characterization prop.
Your component'due south template section should now look like this:
<template > <div > <input blazon = "checkbox" id = "todo-detail" /> <label for = "todo-item" > {{label}} </label > </div > </template > Go dorsum to your browser and you'll see the todo item rendered as before, but without a characterization (oh no!). Go to your browser's DevTools and you'll see a warning along these lines in the console:
[Vue warn]: Missing required prop: "label" found in ---> <ToDoItem> at src/components/ToDoItem.vue <App> at src/App.vue <Root>
This is because nosotros marked the label equally a required prop, only we never gave the component that prop — we've defined where inside the template nosotros want it used, but we haven't passed it into the component when calling it. Allow's fix that.
Within your App.vue file, add together a label prop to the <to-practise-particular></to-do-item> component, simply like a regular HTML attribute:
<to-do-detail label = "My ToDo Item" > </to-do-detail > Now you lot'll see the label in your app, and the warning won't be spat out in the console again.
And so that's props in a nutshell. Next we'll move on to how Vue persists data country.
Vue'southward data object
If you lot alter the value of the characterization prop passed into the <to-do-item></to-do-item> call in your App component, you lot should meet it update. This is bully. We take a checkbox, with an updatable label. Notwithstanding, we're currently not doing anything with the "done" prop — nosotros can check the checkboxes in the UI, but nowhere in the app are we recording whether a todo detail is really washed.
To achieve this, nosotros want to demark the component'due south washed prop to the checked attribute on the <input> element, so that information technology can serve as a record of whether the checkbox is checked or not. However, it's of import that props serve equally one-style data binding — a component should never alter the value of its own props. There are a lot of reasons for this. In function, components editing props can make debugging a challenge. If a value is passed to multiple children, it could be difficult to rail where the changes to that value were coming from. In improver, changing props can cause components to re-render. And then mutating props in a component would trigger the component to rerender, which may in-plow trigger the mutation over again.
To piece of work around this, nosotros can manage the done state using Vue's data property. The data holding is where yous can manage local country in a component, it lives inside the component object alongside the props property and has the following structure:
data ( ) { render { primal : value } } You'll note that the data property is a function. This is to keep the data values unique for each instance of a component at runtime — the office is invoked separately for each component instance. If you alleged information as simply an object, all instances of that component would share the same values. This is a side-effect of the manner Vue registers components and something yous practise not want.
Y'all utilize this to admission a component's props and other properties from inside data, as y'all may expect. We'll come across an instance of this shortly.
Notation: Considering of the fashion that this works in arrow functions (binding to the parent's context), you wouldn't be able to admission any of the necessary attributes from inside data if y'all used an arrow function. So don't use an arrow office for the information property.
So let's add a data holding to our ToDoItem component. This will return an object containing a unmarried property that we'll phone call isDone, whose value is this.done.
Update the component object like and so:
export default { props : { label : { required : truthful , blazon : String } , done : { default : simulated , blazon : Boolean } } , data ( ) { return { isDone : this .done } ; } } ; Vue does a little magic hither — it binds all of your props directly to the component example, and then we don't accept to call this.props.done. It also binds other attributes (information, which you've already seen, and others like methods, computed, etc.) straight to the example. This is, in role, to make them available to your template. The downwardly-side to this is that you need to proceed the keys unique across these attributes. This is why we called our information aspect isDone instead of done.
So at present we need to adhere the isDone property to our component. In a similar way to how Vue uses {{}} expressions to display JavaScript expressions within templates, Vue has a special syntax to bind JavaScript expressions to HTML elements and components: v-bind . The v-bind expression looks similar this:
v-bind:attribute="expression"
In other words, y'all prefix whatever attribute/prop y'all desire to bind to with 5-demark:. In near cases, you tin can use a shorthand for the 5-bind property, which is to just prefix the aspect/prop with a colon. So :aspect="expression" works the same as v-bind:aspect="expression".
And then in the case of the checkbox in our ToDoItem component, nosotros can use v-bind to map the isDone property to the checked attribute on the <input> element. Both of the following are equivalent:
<input type = "checkbox" id = "todo-detail" v-bind:checked = "isDone" /> <input type = "checkbox" id = "todo-detail" :checked = "isDone" /> You're free to use whichever pattern you would like. It's all-time to keep it consistent though. Because the shorthand syntax is more commonly used, this tutorial volition stick to that pattern.
Then let's do this. Update your <input> chemical element at present to include :checked="isDone".
Test out your component by passing :done="true" to the ToDoItem telephone call in App.vue. Notation that you lot need to apply the five-demark syntax, because otherwise truthful is passed as a cord. The displayed checkbox should be checked.
<template> <div id= "app" > <h1>My To-Practice List< /h1> <ul> <li> <to- do -item characterization= "My ToDo Item" :done= "truthful" > < /to- do -item> < /li> < /ul> < /div> < /template> Try changing true to false and back again, reloading your app in between to see how the country changes.
Giving Todos a unique id
Great! We now have a working checkbox where we can set the state programmatically. However, we can currently merely add one ToDoList component to the folio because the id is hardcoded. This would event in errors with assistive technology since the id is needed to correctly map labels to their checkboxes. To prepare this, nosotros can programmatically set the id in the component data.
We can utilise the lodash package's uniqueid() method to assistance continue the alphabetize unique. This package exports a function that takes in a string and appends a unique integer to the finish of the prefix. This volition exist sufficient for keeping component ids unique.
Permit's add together the package to our project with npm; stop your server and enter the following control into your concluding:
npm install --save lodash.uniqueid Annotation: If you lot prefer yarn, y'all could instead use yarn add together lodash.uniqueid.
We can now import this packet into our ToDoItem component. Add the following line at the peak of ToDoItem.vue'due south <script> element:
import uniqueId from 'lodash.uniqueid' ; Side by side, add an id field to our data property, and so the component object ends up looking like so (uniqueId() returns the specified prefix — todo- — with a unique string appended to it):
import uniqueId from 'lodash.uniqueid' ; export default { props : { label : { required : true , blazon : String } , done : { default : false , type : Boolean } } , information ( ) { return { isDone : this .done, id : uniqueId ( 'todo-' ) } ; } } ; Next, bind the id to both our checkbox's id attribute and the characterization's for attribute, updating the existing id and for attributes every bit shown:
<template> <div> <input type= "checkbox" :id= "id" :checked= "isDone" / > <label : for = "id" > { {label} } < /label> < /div> < /template> Summary
And that will do for this article. At this indicate nosotros accept a nicely-working ToDoItem component that can exist passed a label to display, will store its checked state, and will exist rendered with a unique id each time it is called. You tin can bank check if the unique ids are working by temporarily adding more <to-do-item></to-exercise-item> calls into App.vue, and then checking their rendered output with your browser'due south DevTools.
Now we're ready to add multiple ToDoItem components to our App. In our next article we'll look at calculation a set of todo item information to our App.vue component, which we'll then loop through and brandish inside ToDoItem components using the v-for directive.
In this module
How To Register Vue Components,
Source: https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component
Posted by: loganloyarround.blogspot.com

0 Response to "How To Register Vue Components"
Post a Comment