Vue data() attribute lacking proper assignment of props

I am currently developing a Vue component that needs to update the list of restaurants based on dynamically selected filters by the user.

In order to achieve this, I need to modify the filteredRestaurants in the data() method of my Vue component. However, initially, when the component is rendered, it fetches the restaurant information from the "restaurants" prop.

I attempted to initialize the filteredRestaurants data attribute with the value of the "restaurants" prop as a default. Unfortunately, this caused all stores not to display properly, almost like the "restaurants" prop was being injected after the filteredRestaurants had already been assigned a value.

My question is, how can I pass the "restaurants" prop into filteredRestaurants so that I can later refresh the Vue component when the user modifies the filters?

<template lang="html">
  <div class="test">
    <Filters></Filters>
  <div>
    <ul class="o-list c-stores">
      <Result v-bind:total="restaurants.length" v-bind:open="isOpen" v-on:toggle="toggleRestaurantList"></Result>
      <li v-for="(restaurant, index) in restaurants" class="c-stores__location" :class="{'first': isFirst(index), 'last': isLast(index, restaurants)}">
        <Location :index="index" :store="restaurant" :link="() => setCurrentRestaurant(restaurant)"></Location>
      </li>
    </ul>
  </div>
  </div>
</template>

<script>
import eventHub from './../../event-hubs/storefinder'
import Location from './Location'
import Filters from './Filters'
import Result from './Result'

export default {
  props: ["restaurants", "isOpen", "currentSearch"],
  data() {
    return {
      attributes : [],
   // Here I am assigning the prop
      filteredRestaurants : this.restaurants
    }
  },
  head: {
    title: function () {
      return {
        inner: this.$t('storefinder.overview')
      }
    },
    meta: function functionName() {
      return [{
          name: 'og:title',
          content: this.$t('storefinder.overview') + ' - ' + this.$t('storefinder.name'),
          id: "og-title"
        },
        {
          name: 'description',
          content: this.$t('storefinder.description'),
          id: "meta-description"
        },
        {
          name: 'og:description',
          content: this.$t('storefinder.description'),
          id: "og-description"
        },
      ]
    }
  },
  components: {
    Location,
    Filters,
    Result
  },
  methods: {
    toggleRestaurantList() {
      eventHub.$emit('showRestaurantList');
    },
    setCurrentRestaurant(restaurant) {
      this.trackRestaurantSelect(restaurant.publicNameSlug);
      this.$router.push({
        name: "store",
        params: {
          restaurant: restaurant.publicNameSlug
        }
      });
    },
    trackRestaurantSelect(restaurantName) {
      dataLayer.push({
        'event': 'GAEvent',
        'eventCategory': 'restaurants',
        'eventAction': 'clickResult',
        'eventLabel': restaurantName,
        'eventValue': undefined,
        'searchTerm': this.currentSearch && this.currentSearch.toLowerCase(),
        'amountSearchResults': 1
      });
    },
    created() {
      eventHub.$on('addFilterTheRestaurants', (attribute) => this.attributes.push(attribute));
      eventHub.$on('removeFilterTheRestaurants', (attribute) => this.attributes = this.attributes.filter(item => item !== attribute));
    },
    isLast: function (idx, list) {
      return idx === list.length - 1;
    },
    isFirst: function (idx) {
      return idx === 0;
    },
  }
}
</script>

The only approach that seemed to work was defining filteredRestaurants as a function that returns "restaurants", and then invoking it within the Vue template:

filteredRestaurants(){
  return this.restaurants
}

Any assistance will be greatly appreciated.

Answer №1

It seems to me that you're inquiring about a computed property:

computed: {
  filteredItems() {
    return this.items;
  }
}

This computed property will automatically update every time the value of this.items changes.

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

Troubles encountered with the search bar filter functionality, implementing JS/JQuery within a Laravel blade template

Currently, I have a blade template containing a search bar for filtering purposes. The issue I'm encountering is that the filtering functionality doesn't seem to work as expected after removing Angular from the page entirely. The page is set up ...

Combining Json attributes in Jquery Grouping

My task is to group the displays by sectors, but I couldn't find a method in JSON to achieve this. Below is the code snippet: $(function displays(){ var url = '{% url get_displays %}'; $.getJSON(url, function(data) { var sidebar = ...

Obtain the current date from the data source to utilize in a Vuetify component

I am looking to incorporate a vuetify calendar that highlights today's date. How can I retrieve the current date and assign it as a variable in the data? Below is an example of calendar code from the Vuetify webpage for reference. This particular exa ...

What is the correct way to end this jQuery statement?

I've been working on this for about 6 hours now. I ran it through multiple Lint tools and various other online tests, but I just can't seem to get the statement below to close properly. There's a persistent error showing up on the last line ...

Changing the class of a div in JavaScript from one class to another

On my HTML page, I have a div with a CSS class assigned to it. The goal is to switch the current class for another when a button is clicked. It's crucial that not a single CSS property within the class is altered - the entire class must be replaced en ...

Django: Is there a way to modify the PayPal script for pay upon arrival?

I currently do not wish to accept online payments on my e-commerce site. Instead, I would like the courier to handle package delivery and collection of fees. How can I modify the PayPal script to bypass validations and only register payments upon arrival? ...

How can a PHP script send responseText to AJAX from POST request? I am looking to send a message back with Ajax

I am currently working on setting up a system where Ajax calls upload.php and expects a success or failure message in return. I attempted to use echo "success" in the php script, anticipating that xhr.responseText would capture the message. However, when I ...

Secure API Calls with Prismic while Keeping Access Tokens Hidden

As I delve into the world of building a Vue.js web app, I find myself faced with the challenge of making calls to my Prismic repository without exposing my access token. The Rest API approach outlined here seems promising, but I'm at a loss on how to ...

Having trouble with Vuex in Vue JS when trying to set up a modular store

Currently, I am in the process of building a web application using Vue along with Vuex. Despite being new to Vue, I am attempting to integrate Vuex into my Vue application. However, I am encountering an issue when using modularised Vuex. In my project, th ...

Top method for organizing an array based on an object's property and displaying the outcome

I encountered a problem for which I couldn't find an immediate solution. I have an array of objects representing products, with each product having a category property. My goal is to group these products by their categories. After some trial and error ...

Choose options according to a different select in VueJS Laravel

As a VueJs beginner working with Laravel, I am struggling to display categories dynamically when selecting a collection. I am making API calls using Axios, but I can't quite get it to work correctly. Any assistance would be greatly appreciated. <di ...

IntelliJ Community offers comprehensive support for React.js development

Looking for a free React.js plugin with features like syntax highlighting and autocomplete that can be used in IntelliJ Community edition. Considering migrating from Ultimate license to Community edition. Found some answers on stackoverflow but none were ...

What causes offsetHeight to be less than clientHeight?

INFORMATION: clientHeight: Retrieves the height of an element, taking into account padding offsetHeight: Obtains the height of an element, considering padding, border, and scrollbar Analyzing the Data: The value returned by offsetHeight is expected to ...

An error warning was triggered on Cloud 9 IDE while using Socket.io: Error message displaying "Error: listen EACCES."

I am currently working in the Cloud 9 IDE and encountering an issue. The specific error message I am seeing is: warn: error raised: Error: listen EACCES In my code, I am utilizing the Port specified by Cloud 9 for listening: process.env.PORT Below is t ...

Strange Node.js Issue

I don't have much experience with node.js, but I had to use it for launching on Heroku. Everything was going smoothly until a few days ago when suddenly these errors started appearing. Error: /app/index.jade:9 7| meta(name='viewport', co ...

Currently trapped within the Javascript Fizzbuzz application on Codecademy

These are the instructions from Codecademy that need to be followed: Display the numbers from 1 to 20. If a number is divisible by 3, show "Fizz". If a number is divisible by 5, display "Buzz". If a number is divisible both by 3 and 5, then output "Fiz ...

What is the best way to incorporate Twitter Bootstrap CSS and Javascript into a basic VueJS project?

vue init webpack helloworld npm run dev I am thrilled to have a new Vue project. I am wondering how I can seamlessly incorporate the latest version of Twitter Bootstrap into my project, both CSS and Javascript. I attempted to install it using NPM and re ...

What are the best practices for utilizing ESM only npm packages alongside traditional npm packages within a single JavaScript file?

Hey there, I'm fairly new to web development and I encountered a problem when trying to require two packages, franc and langs, in my index.js file. It turns out that franc is now an ESM only package, requiring me to import it and mention type:module i ...

Searching for a single cell within an HTML table

I've been on the hunt for a code that can search through a table and show just one cell. I tried creating my own, but finally stumbled upon one that seems to work perfectly, except for one hiccup. When the search bar is cleared, it displays the first ...

Leveraging jQuery plugin within a React ecosystem

While utilizing semantic react, I found myself in need of a date picker. Fortunately, I stumbled upon this library: https://github.com/mdehoog/Semantic-UI-Calendar However, I am unsure how to incorporate it into my react-based project since it's not ...