Exploring the power of computed properties in VueJS for creating search filters

I recently started working on a Vue project where I developed a Vue component that showcases a collection of different blogs. To achieve this, the component imports a JavaScript file that contains an array with all the details pertaining to each blog.

One of the key features I implemented is linking an HTML input field to a computed property. This allows users to search for specific blogs within the list. Upon entering a search query, the for loop dynamically filters through the blog listings and displays only the relevant results. However, I encountered an issue where upon typing a search query, all content disappears and an error message appears in the console stating "Cannot read property 'match' of undefined." What could be causing this problem?

Here's a snippet of my code:

<ul>
  <li v-for="blog in filteredBlogs">
      {{blog.blogName}}
  </li>
</ul>


import blogs from "./../data/blogs";
export default {
    data() {
        return {
            blogs: blogs,
            search:'',
        };
    },
    computed: {
      filteredBlogs:function(){
        return this.blogs.filter((blog) => {
           return blog.blogName.match(this.search);
        });
      }
    }
};

Answer №1

When you use this.blogs.filter( ... ), the keyword this is pointing to the current Vue instance. Therefore, Vue searches for blogs within the data object but it does not find it there.

Without examining the rest of your application, it's unclear why you are importing blogs and assigning it to the clubs key in your Vue instance. To solve the issue, you can modify your filteredBlogs computed property by changing it to either:

  1. this.clubs.filter( ... ), OR
  2. blogs.filter( ... )

For a visual example, refer to this functional JS Fiddle link: https://jsfiddle.net/voveson/7awythx8/8/

Answer №2

In your Vue instance, make sure you use blogs.filter instead of this.blogs.filter when importing blogs from the file system.

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

The Vue.js error message "Unable to access property 'array_name' as it is undefined" indicates an issue with

I'm currently working on fetching data using Axios requests and storing it in an array. Below is the code I have been using: props: [ 'products', ], data: function () { return { algolia: '', pro ...

Add a new variable to the data in a jQuery ajax request for each request with any updates

I've encountered an issue with the code below, which is meant to add additional data to any ajax request made by my app. It works fine when the page first loads, but because my application is single-page and ajax-based, I need the updated variable val ...

Utilizing jQuery to apply a class to a targeted element when clicked

I'm currently working on animating a menu item where it expands to the left when hovered over, and contracts back when the mouse moves out. This part is functioning as expected. Additionally, I am trying to apply a specific color to the button by add ...

Updating Span or Div content by ID using Jquery and Ajax without needing to reload the page

Here is the code snippet I am working with: <span class='numberofthings' id='123456'> Things: ".$things."</span> Along with the following JavaScript / Ajax code: function click(obj) { $.ajax({ var id = 123456 ...

The absence of a backslash in the JSON string is noticed upon uploading it to the database

After using the JSON.stringify() method in JavaScript to convert my JSON object into a JSON string, I insert it into a database via AJAX posting to a PHP file. $("#saveToDatabase").click(function(){ var place = searchBox.getPlaces(); var locati ...

Creating a clickable link that dynamically updates based on the span and id values, and opens in a new browser tab

I am attempting to create a clickable URL that opens in a new window. The URL is being displayed and updated on my HTML page in the following manner: Python Code: def data_cb(): return jsonify(waiting=await_take_pic()) Javascript Code: jQuery(d ...

Encountering an Unspecified Error in JavaScript while rapid-clicking on a RadGrid with a DetailTable

When testing, I am using Internet Explorer 11. Within a RadGrid control, I have a list of Groups (groupId, groupName) displayed. Each Group includes a DetailTable with the GroupMembers (memberId, groupId, memberName). The RadGrid is located in a Content ...

Can a WordPress post category be active without being displayed on the website?

I want to showcase different categories in both full posts and post excerpts, while also using hidden categories to organize the display of posts throughout the site. For instance, I may have a 'featured' category that is assigned to various pos ...

Wait to fade in until the fade out process is completely finished

When I click on a button, the old box fades out and the new box fades in. However, I want to ensure that the .fadeIn() only happens once the .fadeOut() is complete. This will prevent two containers from being displayed simultaneously. Any suggestions on ...

Cannot access the Promise value beyond the Axios request

I've been trying to retrieve my value and display it on my vue side, but I can't seem to figure it out. Here's my getter in the state file (vuex) getTotalPrice: (state) => { var totalPrice = axios.get("http://" + url + ...

Having trouble accessing a local JSON file in electron-vue

I am attempting to retrieve a local JSON file in my project. I have tried the following: import axios from 'axios'; import userDataJson from './../data/userData.json'; export const userDataControllerMixin = { data() { return { ...

Website experiences technical difficulties but database remains up-to-date

I previously made a similar post, but I have not resolved the issue yet. Here is the output from my terminal: 23 Dec 22:31:23 - Serving request for url[GET] /team 23 Dec 22:31:23 - Successfully created team with Name : Japan 23 Dec 22:31:23 - Serving re ...

Mastering the use of JavaScript callbacks without relying on the jQuery library

I've been working with jquery and javascript for quite a while now. I rarely code in pure javascript, but this time I need to understand callbacks in javascript. It seems like a simple case, but I just can't wrap my head around it. I not only wan ...

Attempting to transform Go Pro GYRO data into rotational values using Three.js

I am currently working on converting gyro data from Go Pro to Three.js coordinates in order to project the footage onto the inside of a sphere. My goal is to rotate the sphere and achieve 3D stabilization. https://i.sstatic.net/VYHV6.png The camera' ...

Troubleshooting: MongoDB only updating the initial document

When I try to update the guild document using one of my commands, it only updates the top guild document instead of the specific guild it was sent in. Here's a picture to help illustrate the issue: https://i.sstatic.net/1VRza.png I am looking to upd ...

What could be causing this error in a new Next.js application?

After multiple attempts, my frustration and disappointment in myself are causing a headache. Can someone please assist me? I am trying to create an app using the following command: npx create-next-app@latest --ts Immediately after running next dev, I enco ...

Rails 7 is missing the Toast element from Bootstrap 5

Having some trouble with implementing Bootstrap 5 Toast in Rails 7 for flash messages. Here is the code I am currently using: # application.html.erb <head> ... <%= javascript_importmap_tags %> <script> const toastElList = document.que ...

What are the steps to effectively utilize an interface within a TypeScript file that contains its own internal import?

Currently, I am in the process of developing a React JavaScript project using WebStorm and attempting to enable type hinting for our IDEs (including VS Code) by utilizing TypeScript interfaces and JSDoc annotations. Our goal is to potentially transition to ...

Struggling to implement a sidebar in HTML using jQuery and running into issues?

I am struggling to create a template that includes a navbar, sidebar, and other elements that can be used across multiple HTML files. Despite trying different approaches, including changing the jQuery version and downloading jQuery, I am unable to make it ...

Using Handlebars to incorporate altered ajax information into a template

Currently, I am exploring ways to utilize manipulated data from an ajax request in conjunction with Handlebars. Within my database, the data is stored as an object like so: {"1 year":"$4.95", "2 years":"$3.95"} My objective now is to make use of this d ...