Home > OS >  Why is this computed() supposed to filter a listof items if anything is writen in a text input not w
Why is this computed() supposed to filter a listof items if anything is writen in a text input not w

Time:01-06

I have this super simple vue3 App, it works kinda like a to-do app, you add an item, and it pushes into an Array which is displayed in Screen. I set a <input/ type="text" with a v-model="" and made a computed which works over that array. The logic is very simple, it has a .filter and a conditional with a return for the match case and the return of the original Array if the input is empty.

<template>
   <div >
       <form @submit.prevent="addItem(item)">
           <div >
               <label for="item">
                   <input type="text" v-model="item" id="item" placeholder="New Item" required>
               </label>
               {{ item }}
               <button :disabled="!item.length" type="submit">Add Item</button>
           </div>
       </form>
       <div >
           <label for="filter-items">
               <input type="text" id="filter-items" placeholder="Filter Items" required  v-model="filterText">
           </label>
       </div>
       {{ filterText }}
       
       <h2>Items List</h2>
       <div >
       <div >
            <b>
                <p>Unpacked</p>
            </b>
           <ul>
               <li v-for="fitem in filteredvalues" :key="fitem">
                   <button @click="deleteItem(item)">Delete item</button>
                   {{ fitem }}
               </li>
           </ul>
       </div>
   </div>
   </div>
</template>

<script setup>
import { ref, computed } from 'vue'
const item = ref('');
const packedItemsArray = ref([]);

function addItem (item) {
   unpackedItemsArray.value.push(item);
};

const filterText = ref('')

const filteredvalues = computed(() => {
 if (!filterText.value.length) {
     return unpackedItemsArray.value
   } else {
     unpackedItemsArray.value.filter( val => val == filterText.value)
 }   
})

const deleteItem = () => {
   return unpackedItemsArray.value.filter((val) => val != it )
}
</script>

The weird thing that I observed is that a console.log() of filterText.value inside the computed returns me an undefined, is that the problem? Async issue?

Any suggestion is highly appreciated! thanks in advence!

CodePudding user response:

You forgot a return statement on line:

unpackedItemsArray.value.filter( val => val == filterText.value)

You should change it to:

return unpackedItemsArray.value.filter( val => val == filterText.value)

CodePudding user response:

From the code I'm seeing here, i don't think the variable "unpackedItemsArray" is defined. That could be the p

  • Related