Tips for utilizing the computed property to search and filter the `ul` content in Vue based on user input

Is there a way to utilize the computed property in order to achieve this? I want the ul element to only display the li items that include my input. For instance, if I type "Ad" into the input field, only the "Add some todos" li item should be displayed. And when I clear the input, all the li items should reappear.

div id="app">
<input v-model="newTodo" v-on:keyup.enter="addTodo">
<ul>
    <li v-for="todo in todos">
        <span>{{ todo.text }}</span>
        <button v-on:click="removeTodo($index)">X</button>
    </li>
</ul>

<script>
    new Vue({
        el: '#app',
        data: {
            newTodo: '',
            todos: [
                {text: 'Add some todos'}
            ]
        },
        methods: {
            addTodo: function () {
                var text = this.newTodo.trim()
                if (text) {
                    this.todos.push({text: text})
                    this.newTodo = ''
                }
            },
            removeTodo: function (index) {
                this.todos.splice(index, 1)
            }
        }
    })
     </script>

https://i.sstatic.net/mQoXr.png

Answer №1

To implement the desired filtering, create a computed method. Replace usages of todos with the computed method in your v-for loop.

new Vue({
  el: '#app',
  data: {
    newTodo: '',
    todos: [{
      text: 'Add some todos'
    }]
  },
  computed: {
    filteredTodos: function() {
      const re = new RegExp(this.newTodo, 'i');
      return this.todos.filter((item) => re.test(item.text));
    }
  },
  methods: {
    addTodo: function() {
      var text = this.newTodo.trim()
      if (text) {
        this.todos.push({
          text: text
        })
        this.newTodo = ''
      }
    },
    removeTodo: function(index) {
      this.todos.splice(index, 1)
    }
  }
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="app">
  <input v-model="newTodo" v-on:keyup.enter="addTodo">
  <ul>
    <li v-for="todo in filteredTodos">
      <span>{{ todo.text }}</span>
      <button v-on:click="removeTodo($index)">X</button>
    </li>
  </ul>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What specific version is indicated by the @next tag for npm packages?

Which version of the foo package will be installed by running this command? npm install foo@next Neither the package.json nor the semver documentation make reference to the use of next. ...

What is the best approach for retrieving the value of a deeply nested JSON object?

Currently, I am developing an application in JavaScript and I have encountered a JSON object. Here is a simplified version of the JSON object: { "data": [ "user": { "pictures"{ "sizes"[ 0: { "link": "http://www" ...

Discover a suitable option or craft one using Mongoose

I'm facing a challenge with handling page ids in my code. The scenario is as follows: Page.findById(pageId).then(page => { const pageId = page.id; .. }); If no page id is provided, I need to select the first available page that meets certain ...

I am interested in creating a class that will produce functions as its instances

Looking to create a TypeScript class with instances that act as functions? More specifically, each function in the class should return an HTMLelement. Here's an example of what I'm aiming for: function generateDiv() { const div = document.crea ...

Dealing with special characters and HTML tags in Vue: How to eliminate them from your code

Resolved using vue-html-secure, much appreciation Received from API - specs: &lt;table&gt;&lt;tr&gt;&lt;td&gt; &lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Диагональ - 19&quot; &lt;/td& ...

Unable to invoke angular ng-click function using jQuery

Can someone assist me in calling ng-click from jQuery correctly? I am having trouble getting it to work. Any guidance on the proper way to do this would be greatly appreciated. HTML: <a ng-click="changeData()">Testing</a> <a ng-click="chan ...

Active positioning within a parent div

I'm having difficulty getting a color picker JavaScript widget to function properly within a webpage that contains unchangeable elements. Some of these elements are causing the color picker to be displayed far below the link once clicked. Here is a si ...

Is it possible in Javascript to verify if a different script has been triggered?

I recently created a pop-out menu for a website using HTML and Javascript. The menu currently has a button that opens a div container with a close button inside it. While the buttons are functioning properly in hiding the div, the elements within the div d ...

Guidelines for calculating the total value within a specific time frame

For my current project, I am using LocalStorage to store an array of dates and costs. When the code localStorage.getItem("todos"); is executed in the console, the output looks like this: "[{"due":"28/10/2017","task":"80"},{"due":"06/10/2017","task":"15"}] ...

The xslt code is failing to invoke the JavaScript function

I am currently utilizing xslt for the transformation of xml to html. Below is an example of an .xml file. <ImportOrganizationUtility-logging> <log-session module-name="ImportOrganizationUtility" end="17:54:06" start="17 ...

Struggling to implement a Rock Paper Scissors game using HTML, CSS Bootstrap4, and JavaScript, specifically facing challenges in getting the function to select a new image

Recently, in my coding class, we were tasked with creating a program that would display images of dice and generate random numbers when the refresh button was clicked. To practice using querySelector and setAttribute, I decided to expand on the lesson by i ...

Display header right button based on a condition in React Native using React Navigation

I am looking to conditionally display the Entypo new-message icon in the top right corner of the header based on a boolean variable (if true, then show the icon in the header). Here is a snippet of code where this functionality can be replicated. Thank y ...

Is there a way to directly set object parameters when a web page loads using JavaScript?

Is there a way to read params values directly into NPAPi plugin? Here is the current JS and form code: <script> var control = document.getElementById('embed'); </script> <form name="formname"> <input type=button value="In ...

Personalized Grid Design for Showcasing Athletic Teams

I am looking to create a custom grid layout that represents the team's Players, separated by their positions (GK, Defense, Midfielders, and Forwards), similar to the image below. The layout should also be responsive like in image 1. Currently, the re ...

In the world of React Redux, there is a peculiar issue where the "return" statement fails to function within a particular Redux Action function, specifically

Attempting to make updates to a customer's name using React-Redux can be a bit tricky. Below is the component code: import React, { useEffect, useState } from "react"; import { Link, Navigate, useParams } from 'react-router-dom'; i ...

Learn the process of sending code to a database using AJAX

I am facing a challenge in saving HTML and Javascript codes to a Database using Ajax. I am unsure about the optimal way to do this. Writing all the codes as Strings for the variable seems cumbersome. Do you have any suggestions to simplify this process? & ...

Struggling to retrieve the values of dynamically generated input fields using a combination of ajax and php

I'm attempting to utilize an Ajax function to post values obtained from a form. Initially, I'm using another Ajax function to populate the form's text box. Then, in order to submit the form data, I'm trying to implement another Ajax fun ...

Dealing with authorization errors in Python using Graphene

My current environment setup is as follows: Frontend @vue/cli 4.1.2 vue-apollo 3.0.2 Backend python 3.8 django 3.0.2 graphene-django 2.8.0 django-graphql-jwt 0.3.0 I am struggling to handle authentication errors when the token expires. For instanc ...

Enter the text value into the input field using live search through AJAX

I stumbled upon this AJAX Live Search PHP script that functions perfectly. Here is the Live Preview. However, instead of opening a new window when clicked, I want the text of the clicked element to be placed in the search box. After modifying the search.ph ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...