Is there a way to display all articles within an array while utilizing a computed property to sort through outcomes on VueJS?

I am currently utilizing VueJS to display a collection of articles. Additionally, I have integrated filters that utilize checkboxes and a computed property to refine the display of articles based on the selected tag.

However, I am interested in incorporating an 'All' tag that would clear any previously selected filter tags (such as Sports/Schools). Is it feasible to achieve this? If so, what steps should I take? I appreciate any guidance on this matter.

var app = new Vue({
  el: '#app',
  data: {
    tags: ['all', 'sports', 'schools'],
    articles: [
      {tags: ['sports'], name: 'Why sports is fun'},
      {tags: ['sports', 'schools'], name: 'How sports helps schools'},
      {tags: ['schools'], name: 'Why students attend school'}
    ],
    selectedTags: []
  },
  computed: {
    activeArticles: function() {
      if(this.selectedTags.length == 0) return this.articles;

      var activeArticles = [];
      var filters = this.selectedTags;

      this.articles.forEach(function(article) {

        function articleContainsFilter(filter) {
          return article.tags.indexOf(filter) != -1;
        }

        if(filters.every(articleContainsFilter)) {
          activeArticles.push(article);
        }
      });
      return activeArticles;
    }
  }
});

Subsequently, the HTML structure is depicted below;

<div id="app">

  <label for="showAllArticles">All</label>
  <input type="checkbox" value="showAllArticles">

  <div v-for="tag in tags">
    <input type="checkbox" value="{{ tag }}" v-model="selectedTags" id="tag-{{ tag }}">
    <label for="tag-{{ tag }}">{{ tag }}</label>
  </div>

  <p v-show="selectedTags.length != 0">
    Filters: <span v-for="tag in selectedTags" class="label">{{ tag }}</span>
  </p>

  <ul>
    <li v-for="article in activeArticles">{{ article.name }}</li> 
  </ul>

</div>

Answer №1

Modify the activeArticles function to display all articles when the all tag is chosen

    activeArticles: function() {
      // Updated if statement
      if(this.selectedTags.length == 0 || this.selectedTags.includes('all') )return this.articles;

      var activeArticles = [];
      var filters = this.selectedTags;

      this.articles.forEach(function(article) {

        function articleContainsFilter(filter) {
          return article.tags.indexOf(filter) != -1;
        }

        if(filters.every(articleContainsFilter)) {
          activeArticles.push(article);
        }
      });
      return activeArticles;
    }

Answer №2

Simply include the following code snippet

methods: {
    resetFilters(e) {
      if (e.target.checked) {
         this.selectedTags = []
      }
    }
  }

Then, add an onClick event listener with the function resetFilters to the 'All' checkbox element

As a result, the activeArticles computed property will automatically update whenever the selectedTags array is modified.

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

Issue with express-validator returning undefined value on forms set to enctype='multipart/form-data'

Currently, I am developing a login authentication application using basic node.js+express. While extracting values (such as name, email, etc) from the registration page, I utilize express-validator for validation. However, I encounter an issue where all va ...

Is it considered good practice to utilize Vue.js for managing global shared state and implementing for loops outside of components?

Just getting started with Vue.JS and experimenting with creating two lists of books (read and unread) from a shared object in the global data state. This is my approach - working demo (works like a charm! However, I'm wondering if this is considered ...

I am facing an issue with uploading files to my designated directory through Node.js Multer

After creating a web service using node js and implementing a form with React interface that includes user information and file upload, I encountered an issue while attempting to save the file to the specified directory on the node js server using multer. ...

Oops! Looks like something went wrong. The command to install the debug app failed because the emulator could not be launched. This could be due to the fact that no emulators were found

I'm in need of assistance to resolve these issues Encountered an error while trying to install the app. Please ensure that your Android development environment is properly configured: https://reactnative.dev/docs/environment-setup. Error: Command fai ...

Having trouble with AngularJS? Ng-switch not updating after ng-click?

Initially in my code, I check if a user has the ability to flag a discussion. If they do, I use ng-switch where upon flagging, a success message is displayed: <div ng-if="canFlag(discussion)"> <div ng-switch="isFlagging" ng-click="fla ...

Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties: public id: number; public modelId: number; public modelName: string; Now consider we have an object that looks like this {id: 1, modelId: 1, modelName: "4"} What is the best way to assign e ...

Next.js allows for passing dynamically loaded server-side data to all components for easy access

(I've recently started working with Next.js and inherited a project built using it, so please forgive me if this is something obvious that I'm missing) I have a set of data that needs to be loaded server-side on each request. Initially, I had im ...

Tips for successfully transferring the nested service and retrieving the response from an Angular factory to a controller

After making the Http Request and receiving the response from the first Service call, I then pass that response from the first service into the second service and receive the response back to the controller. Now that I have the response, I need to find a ...

Issue encountered while working with PostgreSQL and Sequelize when using the array_append function

I'm encountering issues with the following code snippet let user = req.user.id; await MyTable.update( {'interested': Sequelize.fn('array_append', Sequelize.col('interested'), user)}, {'where ...

Change the Vue3 PrimeVue theme or CSS file with a simple click or upon page load

One way to incorporate themes is by importing them in the main.js file at the root of the app: import 'primevue/resources/themes/arya-orange/theme.css'; However, I am exploring ways to dynamically switch CSS files based on the user's system ...

Create a layered structure using a specified path

I am aiming to create a function that can accept an object path, like { 'person.data.info.more.favorite': 'smth' } and then output a nested object: { person: { data: { info: { more: { favorite: 'smth& ...

Fluctuating price depending on the selected choice

Hello, I am in the process of updating the price based on the selection made from the options. I am unsure whether to use JavaScript or Ajax for this task and how to go about it. Can someone please guide me? <tr> <td width="160">Price:</td ...

How can I open a new window, redirect the current one, and bring focus to the new window using JavaScript?

Trying to troubleshoot a problem I'm having with the following setup: - Using SAP Portal, I am launching an HTML page containing this code. - The goal is for the HTML page to open a new window. - Once the new window opens, the original HTML page ...

Unable to adjust the width of the react-select component

I've been struggling to adjust the width of the select element but no matter what I try, it remains at a default width of about 75px. const CustomContainer = styled('div')` width: 100%; height: 100%; display: flex; flex-flow: row wr ...

Loop through the JSON object at a depth of three levels

Can someone please help me with this issue that's been bothering me? I'm currently working with Facebook's Graph API to access data. I need to find out how to retrieve the application name. { "data": [ { "messag ...

Transmitting a plethora of information using jQuery

Here's the code I currently have for sending data: var test={imagename:"apple.jpg",x:"13",y:"33"}; $.ajax({ type: "POST", url: "some.php", data: test, success: function(response){ console.log(response); } }); ...

Tips for eliminating parameter from url with vue-router

I find myself dealing with multiple parameters in the URL. Recently, I encountered an issue while trying to add a new parameter using the code below: this.$router.push({query: Object.assign({}, this.$route.query, {cities: '1,45'})}); Despite my ...

When the Jqueryui dialog is closed, it effectively terminates the current JavaScript thread

Hello there, I'm currently facing an issue with closing my jQuery dialog box. The situation involves a comet connection that sends messages to my browser. My goal is to perform certain actions upon receiving a message, close the dialog, and then conti ...

Vue 3 - Compelled to utilize any data type with computedRef

Recently, I've been diving into Vue/Typescript and encountered a puzzling error. The issue revolves around a class named UploadableFile: export class UploadableFile { file: File; dimensions: Ref; price: ComputedRef<number>; ... constr ...

Experimenting with API request in Vue using Moxios

I am facing an issue with testing an API call that occurs in the "mounted" lifecycle hook. In my single file component, I am responsible for presenting information about an "Owner". The functionality works as expected in the browser. <template> & ...