Adding a new todo form: Vue events, methods, and models

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.

Creating a New To-Do form

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.

  1. In your components folder, create a new file called ToDoForm.vue .
  2. Add a blank <template> <script> tag like before:
    <template></template>
    <script>
      export default {};
    </script>
    
    								
  3. Let's add in an HTML form that lets you enter a new todo item and submit it into the app. We need a <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).
  4. Let's load this component into our app. Go back to App.vue and add the following import statement just below the previous one, inside your <script> 元素:
    import ToDoForm from './components/ToDoForm';
    
    								
  5. You also need to register the new component in your App component — update the components property of the component object so that it looks like this:
    components: {
      ToDoItem,
      ToDoForm
    }
    
    								
  6. Finally for this section, render your 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.

Our todo list app rendered with a text input to enter new todos

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.

Creating a method & binding it to an event with v-on

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.

  1. In this component, we need to add an 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')
           }
       }
    }
    
    								
  2. Next we need to bind the method to our <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">
    
    								
  3. When you run this, the app still posts the data to the server, causing a refresh. Since we're doing all of our processing on the client, there's no server to handle the postback. We also lose all local state on page refresh. To prevent the browser from posting to the server, we need to stop the event’s default action while bubbling up through the page ( 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() .
    In this case, we need to use the .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() 方法。

Binding data to inputs with v-model

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.

  1. 添加 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: ""
        };
      }
    };
    
    								
  2. We now need some way to attach the value of the 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.

  3. Let's test out our use of 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);
      }
    },
    
    								
  4. Now go back to your running app, add some text to the <input> field, and click the "Add" button. You should see the value you entered logged to your console, for example:
    Label value: My value
    								

Changing 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.

Passing data to parents with custom events

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.

  1. Replace the console.log() onSubmit() method with the following:
    this.$emit("todo-added");
    
    								
  2. Next, go back to 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');
        }
      }
    };
    
    								
  3. Next, add an event listener for the 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>
    
    								
  4. When you submit your 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)
    }
    
    								
  5. To actually pick up this data inside 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.

Adding the new todo into our data

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.

  1. Update your addToDo() method like so:
    addToDo(toDoLabel) {
      this.ToDoItems.push({id:uniqueId('todo-'), label: toDoLabel, done: false});
    }
    
    								
  2. Try testing your form again, and you should see new to-do items get appended to the end of the list.
  3. Let's make a further improvement before we move on. If you submit the form while the input is empty, todo items with no text still get added to the list. To fix that, we can prevent the todo-added event from firing when name is empty. Since name is already being trimmed by the .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);
    }
    
    								
  4. Try your form again. Now you will not be able to add empty items to the to-do list.

Our todo list app rendered with a text input to enter new todos

使用 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.

In this module

发现此页面有问题吗?

最后修改: , 由 MDN 贡献者

  1. Complete beginners start here!
  2. Web 快速入门
    1. Getting started with the Web overview
    2. 安装基本软件
    3. What will your website look like?
    4. 处理文件
    5. HTML 基础
    6. CSS 基础
    7. JavaScript 基础
    8. 发布您的网站
    9. How the Web works
  3. HTML — Structuring the Web
  4. HTML 介绍
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. 多媒体和嵌入
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the Web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML 表格
    1. HTML tables overview
    2. HTML table basics
    3. HTML Table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. CSS — Styling the Web
  8. CSS 第一步
    1. CSS first steps overview
    2. What is CSS?
    3. Getting started with CSS
    4. How CSS is structured
    5. How CSS works
    6. Using your new knowledge
  9. CSS 构建块
    1. CSS building blocks overview
    2. Cascade and inheritance
    3. CSS 选择器
    4. The box model
    5. Backgrounds and borders
    6. Handling different text directions
    7. Overflowing content
    8. Values and units
    9. Sizing items in CSS
    10. Images, media, and form elements
    11. Styling tables
    12. Debugging CSS
    13. Organizing your CSS
  10. 样式化文本
    1. Styling text overview
    2. Fundamental text and font styling
    3. Styling lists
    4. Styling links
    5. Web fonts
    6. Assessment: Typesetting a community school homepage
  11. CSS 布局
    1. CSS layout overview
    2. Introduction to CSS layout
    3. Normal Flow
    4. Flexbox
    5. Grids
    6. Floats
    7. 位置
    8. Multiple-column Layout
    9. Responsive design
    10. Beginner's guide to media queries
    11. Legacy Layout Methods
    12. Supporting Older Browsers
    13. Fundamental Layout Comprehension
  12. JavaScript — Dynamic client-side scripting
  13. JavaScript 第一步
    1. JavaScript first steps overview
    2. What is JavaScript?
    3. A first splash into JavaScript
    4. What went wrong? Troubleshooting JavaScript
    5. Storing the information you need — Variables
    6. Basic math in JavaScript — Numbers and operators
    7. Handling text — Strings in JavaScript
    8. Useful string methods
    9. 数组
    10. Assessment: Silly story generator
  14. JavaScript 构建块
    1. JavaScript building blocks overview
    2. Making decisions in your code — Conditionals
    3. Looping code
    4. Functions — Reusable blocks of code
    5. Build your own function
    6. Function return values
    7. 事件介绍
    8. Assessment: Image gallery
  15. 引入 JavaScript 对象
    1. Introducing JavaScript objects overview
    2. Object basics
    3. 对象原型
    4. Object-oriented programming concepts
    5. Classes in JavaScript
    6. Working with JSON data
    7. Object building practice
    8. Assessment: Adding features to our bouncing balls demo
  16. 异步 JavaScript
    1. Asynchronous JavaScript overview
    2. General asynchronous programming concepts
    3. Introducing asynchronous JavaScript
    4. Cooperative asynchronous Java​Script: Timeouts and intervals
    5. Graceful asynchronous programming with Promises
    6. Making asynchronous programming easier with async and await
    7. Choosing the right approach
  17. 客户端侧 Web API
    1. 客户端侧 Web API
    2. Introduction to web APIs
    3. Manipulating documents
    4. Fetching data from the server
    5. Third party APIs
    6. Drawing graphics
    7. Video and audio APIs
    8. Client-side storage
  18. Web forms — Working with user data
  19. Core forms learning pathway
    1. Web forms overview
    2. Your first form
    3. How to structure a web form
    4. Basic native form controls
    5. The HTML5 input types
    6. Other form controls
    7. Styling web forms
    8. Advanced form styling
    9. UI pseudo-classes
    10. Client-side form validation
    11. Sending form data
  20. Advanced forms articles
    1. How to build custom form controls
    2. Sending forms through JavaScript
    3. CSS property compatibility table for form controls
  21. Accessibility — Make the web usable by everyone
  22. Accessibility guides
    1. Accessibility overview
    2. What is accessibility?
    3. HTML: A good basis for accessibility
    4. CSS and JavaScript accessibility best practices
    5. WAI-ARIA basics
    6. Accessible multimedia
    7. Mobile accessibility
  23. Accessibility assessment
    1. Assessment: Accessibility troubleshooting
  24. Tools and testing
  25. Client-side web development tools
    1. Client-side web development tools index
    2. Client-side tooling overview
    3. Command line crash course
    4. Package management basics
    5. Introducing a complete toolchain
    6. Deploying our app
  26. Introduction to client-side frameworks
    1. Client-side frameworks overview
    2. Framework main features
  27. React
    1. Getting started with React
    2. Beginning our React todo list
    3. Componentizing our React app
    4. React interactivity: Events and state
    5. React interactivity: Editing, filtering, conditional rendering
    6. Accessibility in React
    7. React resources
  28. Ember
    1. Getting started with Ember
    2. Ember app structure and componentization
    3. Ember interactivity: Events, classes and state
    4. Ember Interactivity: Footer functionality, conditional rendering
    5. Routing in Ember
    6. Ember resources and troubleshooting
  29. Vue
    1. Getting started with Vue
    2. Creating our first Vue component
    3. Rendering a list of Vue components
    4. Adding a new todo form: Vue events, methods, and models
    5. Styling Vue components with CSS
    6. Using Vue computed properties
    7. Vue conditional rendering: editing existing todos
    8. Focus management with Vue refs
    9. Vue resources
  30. Svelte
    1. Getting started with Svelte
    2. Starting our Svelte Todo list app
    3. Dynamic behavior in Svelte: working with variables and props
    4. Componentizing our Svelte app
    5. Advanced Svelte: Reactivity, lifecycle, accessibility
    6. Working with Svelte stores
    7. TypeScript support in Svelte
    8. Deployment and next steps
  31. Angular
    1. Getting started with Angular
    2. Beginning our Angular todo list app
    3. Styling our Angular app
    4. Creating an item component
    5. Filtering our to-do items
    6. Building Angular applications and further resources
  32. Git and GitHub
    1. Git and GitHub overview
    2. Hello World
    3. Git Handbook
    4. Forking Projects
    5. About pull requests
    6. Mastering Issues
  33. Cross browser testing
    1. Cross browser testing overview
    2. Introduction to cross browser testing
    3. Strategies for carrying out testing
    4. Handling common HTML and CSS problems
    5. Handling common JavaScript problems
    6. Handling common accessibility problems
    7. Implementing feature detection
    8. Introduction to automated testing
    9. Setting up your own test automation environment
  34. Server-side website programming
  35. 第一步
    1. First steps overview
    2. Introduction to the server-side
    3. Client-Server overview
    4. Server-side web frameworks
    5. Website security
  36. Django Web 框架 (Python)
    1. Django web framework (Python) overview
    2. 介绍
    3. 设置开发环境
    4. Tutorial: The Local Library website
    5. Tutorial Part 2: Creating a skeleton website
    6. Tutorial Part 3: Using models
    7. Tutorial Part 4: Django admin site
    8. Tutorial Part 5: Creating our home page
    9. Tutorial Part 6: Generic list and detail views
    10. Tutorial Part 7: Sessions framework
    11. Tutorial Part 8: User authentication and permissions
    12. Tutorial Part 9: Working with forms
    13. Tutorial Part 10: Testing a Django web application
    14. Tutorial Part 11: Deploying Django to production
    15. Web application security
    16. Assessment: DIY mini blog
  37. Express Web Framework (node.js/JavaScript)
    1. Express Web Framework (Node.js/JavaScript) overview
    2. Express/Node introduction
    3. Setting up a Node (Express) development environment
    4. Express tutorial: The Local Library website
    5. Express Tutorial Part 2: Creating a skeleton website
    6. Express Tutorial Part 3: Using a database (with Mongoose)
    7. Express Tutorial Part 4: Routes and controllers
    8. Express Tutorial Part 5: Displaying library data
    9. Express Tutorial Part 6: Working with forms
    10. Express Tutorial Part 7: Deploying to production
  38. Further resources
  39. Common questions
    1. HTML questions
    2. CSS questions
    3. JavaScript questions
    4. Web mechanics
    5. Tools and setup
    6. Design and accessibility