简体   繁体   中英

Filtering items using a condition (vue.js)

This is now solved

The problem

I am trying to make a filter that does this. Gets 'name' from session storage and matches it with 'name' on product.

I'm storing all 'logged in' user data on 'sessionStorage' for practice.
I'm storing all the 'products' in 'localStorage'

I'm just doing this as a small project to understand and practice vue & js.

Basically if the product has been created by user x, upon login, user x should only be able to see the products he listed and not the rest of the products.

This is what I can do

I can get the user info from sessionStorage and when creating a product, the user 'name' is passed on along with the product details.


I can also retrieve all the products from localStorage.



I don't know how to come up with a filter using vue.js that does this.

Some code sample would really help me understand whats going on.

Additionally, I want to display the results in html.

Thanks in advance.

    },
    computed: {
        filteredProducts() {
            this.products.filter(x => x.name === this.loggedUser[0].user);
        }
    },

});```



  [1]: https://i.stack.imgur.com/W7PMf.png
computed: {
  filteredProducts() {
    return this.products.filter(x => x.name === this.loggedUser[0].text); // text or user, whichever field is for username
  },
},

After that show the list in html use v-for .

<p v-if="filteredProducts.length === 0">No products found</p>
<li v-for="(product, key) in filteredProducts" :key="key">Product: {{ product.description }}, Price {{ product.price }} <button @click="deleteProduct(key)">Delete</button></li>

add delete method

methods: {
 // ...
 deleteProduct(index) {
        this.products.splice(index, 1);
 },
}

I think this may work from you (given what you have provided above)

computed: {
  filteredProducts () {
    return this.products.filter(function (item) {
      return (item.name === this.loggedUser[0].name)
    }
  }
}

Basically, we are filtering the products based on the name that is tagged on that list with the loggedUser name.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM