We now have sample data in place, and a loop that takes each bit of data and renders it inside a
ToDoItem
in our app. What we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text
<input>
, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. This is what we'll cover in this article.
| Prerequisites: |
Familiarity with the core
HTML
,
CSS
,和
JavaScript
languages,
knowledge of the
terminal/command line
.
Vue components are written as a combination of JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure. For installation, and to use some of the more advanced features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. |
|---|---|
| Objective: | To learn about handling forms in Vue, and by association, events, models, and methods. |
We now have an app that displays a list of to-do items. However, we can't update our list of items without manually changing our code! Let's fix that. Let's create a new component that will allow us to add a new to-do item.
ToDoForm.vue
.
<template>
和
<script>
tag like before:
<template></template>
<script>
export default {};
</script>
<form>
采用
<label>
,
<input>
,和
<button>
. Update your template as follows:
<template>
<form>
<label for="new-todo-input">
What needs to be done?
</label>
<input
type="text"
id="new-todo-input"
name="new-todo"
autocomplete="off"
/>
<button type="submit">
添加
</button>
</form>
</template>
So we now have a form component into which we can enter the title of a new todo item (which will become a label for the corresponding
ToDoItem
when it is eventually rendered).
App.vue
and add the following
import
statement just below the previous one, inside your
<script>
元素:
import ToDoForm from './components/ToDoForm';
components
property of the component object so that it looks like this:
components: {
ToDoItem,
ToDoForm
}
ToDoForm
component inside your App by adding the
<to-do-form />
element inside your
App
's
<template>
, like so:
<template>
<div id="app">
<h1>My To-Do List</h1>
<to-do-form></to-do-form>
<ul>
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item :label="item.label" :done="item.done" :id="item.id"></to-do-item>
</li>
</ul>
</div>
</template>
Now when you view your running site, you should see the new form displayed.
If you fill it out and click the "Add" button, the page will post the form back to the server, but this isn’t really what we want. What we actually want to do is run a method on the
submit
event
that will add the new todo to the
ToDoItem
data list defined inside
App
. To do that, we'll need to add a method to the component instance.
To make a method available to the
ToDoForm
component, we need to add it to the component object, and this is done inside a
方法
property to our component, which goes in the same place as
data()
,
props
, etc. The
方法
property holds any methods we might need to call in our component. When referenced, methods are fully run, so it's not a good idea to use them to display information inside the template. For displaying data that comes from calculations, you should use a
computed
property, which we'll cover later.
onSubmit()
method to a
方法
property inside the
ToDoForm
component object. We'll use this to handle the submit action.
Add this like so:
export default {
methods: {
onSubmit() {
console.log('form submitted')
}
}
}
<form>
元素的
submit
event handler. Much like how Vue uses the
v-bind
syntax for binding attributes, Vue has a special directive for event handling:
v-on
。
v-on
directive works via the
v-on:event="method"
syntax. And much like
v-bind
, there’s also a shorthand syntax:
@event="method"
.
We'll use the shorthand syntax here for consistency. Add the
submit
handler to your
<form>
element like so:
<form @submit="onSubmit">
Event.preventDefault()
, in vanilla JavaScript). Vue has a special syntax called
event modifiers
that can handle this for us right in our template.
Modifiers are appended to the end of an event with a dot like so:
@event.modifier
. Here is a list of event modifiers:
.stop
: Stops the event from propagating. Equivalent to
Event.stopPropagation()
in regular JavaScript events.
.prevent
: Prevents the event's default behavior. Equivalent to
Event.preventDefault()
.
.self
: Triggers the handler only if the event was dispatched from this exact element.
{.key}
: Triggers the event handler only via the specified key.
MDN has a list of valid key values
; multi-word keys just need to be converted to kebab case (e.g.
page-down
).
.native
: Listens for a native event on the root (outer-most wrapping) element on your component.
.once
: Listens for the event until it's been triggered once, and then no more.
.left
: Only triggers the handler via the left mouse button event.
.right
: Only triggers the handler via the right mouse button event.
.middle
: Only triggers the handler via the middle mouse button event.
.passive
: Equivalent to using the
{ passive: true }
parameter when creating an event listener in vanilla JavaScript using
addEventListener()
.
.prevent
handler to stop the browser’s default submit action. Add
.prevent
到
@submit
handler in your template like so:
<form @submit.prevent="onSubmit">
If you try submitting the form now, you'll notice that the page doesn't reload. If you open the console, you can see the results of the
console.log()
we added inside our
onSubmit()
方法。
Next up, we need a way to get the value from the form's
<input>
so we can add the new to-do item to our
ToDoItems
data list.
The first thing we need is a
data
property in our form to track the value of the to-do.
data()
method to our
ToDoForm
component object that returns a
label
field. We can set the initial value of the
label
成空字符串。
Your component object should now look something like this:
export default {
methods: {
onSubmit() {
console.log("form submitted");
}
},
data() {
return {
label: ""
};
}
};
new-todo-input
<input>
field to the
label
field. Vue has a special directive for this:
v-model
.
v-model
binds to the data property you set on it and keeps it in sync with the
<input>
.
v-model
works across all the various input types, including check boxes, radios, and select inputs. To use
v-model
, you add an attribute with the structure
v-model="variable"
到
<input>
.
So in our case, we would add it to our
new-todo-input
field as seen below. Do this now:
<input
type="text"
id="new-todo-input"
name="new-todo"
autocomplete="off"
v-model="label" />
注意:
You can also sync data with
<input>
values through a combination of events and
v-bind
attributes. In fact, this is what
v-model
does behind the scenes. However, the exact event and attribute combination varies depending on input types and will take more code than just using the
v-model
shortcut.
v-model
by logging the value of the data submitted in our
onSubmit()
method. In components, data attributes are accessed using the
this
keyword. So we access our
label
field using
this.label
.
Update your
onSubmit()
method to look like this:
methods: {
onSubmit() {
console.log('Label value: ', this.label);
}
},
<input>
field, and click the "Add" button. You should see the value you entered logged to your console, for example:
Label value: My value
v-model
behavior with modifiers
In a similar fashion to event modifiers, we can also add modifiers to change the behavior of
v-model
. In our case, there are two worth considering. The first,
.trim
, will remove whitespace from before or after the input. We can add the modifier to our
v-model
statement like so:
v-model.trim="label"
.
The second modifier we should consider is called
.lazy
. This modifier changes when
v-model
syncs the value for text inputs. As mentioned earlier,
v-model
syncing works by updating the variable using events. For text inputs, this sync happens using the
input
event
. Often, this means that Vue is syncing the data after every keystroke. The
.lazy
modifier causes
v-model
要使用
change
event
instead. This means that Vue will only sync data when the input loses focus or the form is submitted. For our purposes, this is much more reasonable since we only need the final data.
To use both the
.lazy
modifier and the
.trim
modifier together, we can chain them, e.g.
v-model.lazy.trim="label"
.
Update your
v-model
attribute to chain
lazy
and
trim
as shown above, and then test your app again. Try for example, submitting a value with whitespace at each end.
We now are very close to being able to add new to-do items to our list. The next thing we need to be able to do is pass the newly-created to-do item to our
App
component. To do that, we can have our
ToDoForm
emit a custom event that passes the data, and have
App
listen for it. This works very similarly to native events on HTML elements: a child component can emit an event which can be listened to via
v-on
.
在
onSubmit
event of our
ToDoForm
, let's add a
todo-added
event. Custom events are emitted like this:
this.$emit("event-name")
. It's important to know that event handlers are case sensitive and cannot include spaces. Vue templates also get converted to lowercase, which means Vue templates cannot listen for events named with capital letters.
console.log()
在
onSubmit()
method with the following:
this.$emit("todo-added");
App.vue
and add a
方法
property to your component object containing an
addToDo()
method, as shown below. For now, this method can just log
To-do added
to the console.
export default {
name: 'app',
components: {
ToDoItem,
ToDoForm
},
data() {
return {
ToDoItems: [
{ id:uniqueId('todo-'), label: 'Learn Vue', done: false },
{ id:uniqueId('todo-'), label: 'Create a Vue project with the CLI', done: true },
{ id:uniqueId('todo-'), label: 'Have fun', done: true },
{ id:uniqueId('todo-'), label: 'Create a to-do list', done: false }
]
};
},
methods: {
addToDo() {
console.log('To-do added');
}
}
};
todo-added
event to the
<to-do-form></to-do-form>
, which calls the
addToDo()
method when the event fires. Using the
@
shorthand, the listener would look like this:
@todo-added="addToDo"
:
<to-do-form @todo-added="addToDo"></to-do-form>
ToDoForm
, you should see the console log from the
addToDo()
method. This is good, but we're still not passing any data back into the
App.vue
component. We can do that by passing additional arguments to the
this.$emit()
function back in the
ToDoForm
组件。
In this case, when we fire the event we want to pass the
label
data along with it. this is done by including the data you want to pass as another parameter in the
$emit()
方法:
this.$emit("todo-added", this.label)
. This is similar to how native JavaScript events include data, except custom Vue events include no event object by default. This means that the emitted event will directly match whatever object you submit. So in our case, our event object will just be a string.
Update your
onSubmit()
method like so:
onSubmit() {
this.$emit('todo-added', this.label)
}
App.vue
, we need to add a parameter to our
addToDo()
method that includes the
label
of the new to-do item.
Go back to
App.vue
and update this now:
methods: {
addToDo(toDoLabel) {
console.log('To-do added:', toDoLabel);
}
}
If you test your form again, you'll see whatever text you enter logged in your console upon submission. Vue automatically passes the arguments after the event name in
this.$emit()
to your event handler.
Now that we have the data from
ToDoForm
available in
App.vue
, we need to add an item representing it to the
ToDoItems
array. This can be done by pushing a new to-do item object to the array containing our new data.
addToDo()
method like so:
addToDo(toDoLabel) {
this.ToDoItems.push({id:uniqueId('todo-'), label: toDoLabel, done: false});
}
.trim
directive, we only need to test for the empty string.
Go back to your
ToDoForm
component, and update the
onSubmit()
method like so. If the label value is empty, let's not emit the
todo-added
事件。
onSubmit() {
if(this.label === "") {
return;
}
this.$emit('todo-added', this.label);
}
v-model
to update an input value
There's one more thing to fix in our
ToDoForm
component — after submitting, the
<input>
still contains the old value. But this is easy to fix — because we're using
v-model
to bind the data to the
<input>
in
ToDoForm
, if we set the name parameter to equal an empty string, the input will update as well.
Update your
ToDoForm
component’s
onSubmit()
method to this:
onSubmit() {
if(this.label === "") {
return;
}
this.$emit('todo-added', this.label);
this.label = "";
}
Now when you click the "Add" button, the "new-todo-input" will clear itself.
Excellent. We can now add todo items to our form! Our app is now starting to feel interactive, but one issue is that we've completely ignored its look and feel up to now. In the next article, we'll concentrate on fixing this, looking at the different ways Vue provides to style components.
最后修改: , 由 MDN 贡献者