VueJS: Refreshing component list data from child component

Consider a Todo list with filtering functionality:

list.vue:

<script>
import TodoItem from './todo_item.vue';
export default {
  components: { TodoItem },
  props: ['selectedPriority'],
  data: {
    items: [
      { name: 'Do shopping', priority: 'high' },
      { name: 'Play games', priority: 'low' }
    ]
  },
  computed: {
    selectedItems: function() {
      if(this.selectedPriority == 'all') {
        return this.items;
      } else {
        var selectedPriority = this.selectedPriority;
        return this.items.filter(function(item) {
          return item.priority == selectedPriority
        });
      }
    }
  },
}
</script>

<template>
  <div>
    <select v-model="selectedPriority">
      <option value="all">All</option>
      <option value="low">Low</option>
      <option value="high">High</option>
    </select>
    <todo-item
      v-for="item in selectedItems"
      :name="item.name"
      :priority="item.priority"
    />
  </div>
</template>

todo_item.vue:

<script>
export default {
  props: ['name', 'priority']
}
</script>
<template>
  <div>
    <p>{{ name }}</p>
    <select v-model="priority">
      <option value="low">Low</option>
      <option value="high">High</option>
    </select>
  </div>
</template>

html:

<list />

If, for instance, the filter is set to all, and I change the priority of Play games to high and switch the filter to high, only Do shopping will be displayed. This is because the priority was not updated in the items collection and it triggered a re-render.

What is the correct method to update collection data from child components in Vue.js?

Answer №1

When using computed properties, you can easily generate and retrieve a refined list.

In this case, the example leverages lodash

data: {
  items: [
    {name: 'product A', price: 100},
    {name: 'product B', price: 50},
    {name: 'product C', price: 250},
    {name: 'product D', price: 342},
  ],
},
computed: {
  sortedProducts() {
    let products = []
    return _.orderBy(this.items, 'price', 'desc');
  },
}

To make changes, simply pass the index from sortedProducts array to the "this.items" array.

Answer №2

I've discovered a solution that seems to be effective - rather than passing all parameters of the todo-item into the component, simply pass the entire object:

    <todo-item
      v-for="item in selectedItems"
      :item="item"
    />

This way, any updates made to the object in the parent collection are automatically reflected.

Do you think this is a good practice in Vue development?

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

Encountering the "Auth0 and Nuxt JS 400 ( Unable to retrieve script source )" error while trying to log in

Recently, I ventured into the world of Nuxt and encountered a 400 error page every time I tried to log in. I followed the instructions directly from the Auth/nuxt Docs with the exception of adding an ENV file. I also made sure to add my Application URIs t ...

How to alter the HTML view in Angular 2 after it has been processed

Here is some Angular 2 code snippet: import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: 'Waiting on port ', }) export class AppComponent { } I want to dynamically add the text "3000" ...

Upon selecting the correct prompt, it fails to respond when I press enter

I attempted to use a multi-search script that I found on a website. I followed the instructions given and made the necessary changes. After saving the file as an HTML document, I opened it in Chrome. However, when I type in a word and hit enter, nothing ha ...

Exploring the variance in performance between lodash's "get" function and traditional "if else" clauses

Imagine you have a TypeScript object with the possibility of elements being undefined. Navigating through a deeply nested structure requires multiple comparisons against undefined values. I wanted to examine the performance difference between using regula ...

The "users" property or method has not been defined in Vue.js applications

During the development of my Vue.js shopping cart, I encountered an issue where I wanted to display the username in a label after the user provided correct information. However, I received the following error in Google Chrome: vue.js:634 [Vue warn]: Prope ...

Is it possible to populate a shopping cart using Vue?

Currently, I am working on integrating a shopping cart feature into a webpage using Vue.js. Upon loading the page, I successfully retrieve a list of items through an API call and display them. However, I am facing challenges in adding items to the cart. ...

Unable to display ChartJs within the same DIV on the webpage

I'm struggling to display the Pie Chart from ChartJs in the correct DIV when I click from the left DIV. Running the chart directly works fine, but I want them both on the same page in separate DIVs. I have separate HTML files for each link and they wo ...

Eliminate values from an array by utilizing either a for loop or a custom filtering function

I need help with removing specific URLs from an array every time they appear. Here is the list of URLs I want to filter out: "https://basueUrl.com/Claim" "https://basueUrl.com/ExplanationOfBenefit" This is my current array: Array= [ "https://b ...

Exploring the nuances between Ruby on Rails and the responses from json and JavaScript ajax

I am interested in learning the most effective method for handling an ajax request. Would it be better to send json data and parse it on the client side (for instance using pure), or should I generate javascript at the server side and send back the respo ...

Inserting a variable into a JSON string

Within my code, I have a basic variable containing strings that are converted into a JSON object. My goal is to create an input field where a person's name can be entered and added to the text. The current setup looks like this var text = '{"st ...

Meteor: Simplifying the process of deleting two documents from separate collections in MongoDB with just one click

There is a possibility that some "news documents" (from one collection) may contain an image (from another collection I'm using cfs:standard-packages and cfs:filesystem for file handling). Here is an example of a news document in the Mongo Database: ...

Do not apply tailwindcss styles to Material-UI

I've been struggling to apply styling from tailwindcss to my MUI button. My setup includes babel and webpack, with the npm run dev script as "webpack --mode development --watch". tailwind.css module.exports = { content: ["./src/**/*.{js, jsx, t ...

Tips for displaying data regarding inertia to Vue components

I have successfully retrieved the message in Vue Inspector, but I am struggling with how to implement it in Vue Components. Take a look at the image link below: https://ibb.co/2KTmstS Despite using the Inertia helper method to send a message to Vue Comp ...

Modifying the status using retrieved JSON information

My goal is to retrieve data from an external API and use it to update the state of my app. Although I can see the data in the console, the state of my app remains unchanged when I try to run setState. class App extends Component { state={ jobs:[] ...

Getting Started with the Basic Example of Redux-Router

Recently, I decided to give redux-router a try and wanted to run the basic example. However, when I tried running the command: npm start I encountered an error message that said: node: bad option: -r Being new to the JavaScript modern ecosystem, I&apos ...

The code splitting feature in Nuxt is currently experiencing issues

Recently, I've started working with nuxtjs and currently have 2 pages set up: -index -map The map page contains a single client-only component, while the default layout includes links to both pages. However, when I build the production version, the ...

The isInvalid property fails to apply red highlighting to the input box in a react-bootstrap form

Working on creating forms using React and react-bootstrap. Currently, my form includes an email field structured like this - https://i.sstatic.net/dlbWn.png Here's the code snippet of how it looks: <Form noValidate autoComplete="off&quo ...

Guide to developing a drop-down menu using the html <select> tag in jquery and dynamically loading it with the data retrieved from an ajax request

I'm stuck on this code snippet: function getSchools(selectedReport){ $("<select id = 'schools' onChange = 'createReport(this)'></select>").insertAfter("#myList") $.ajax({ typ ...

Header cannot be set once they have already been sent

I'm having trouble setting the header in the code snippet below. Even though I've added a return at the end of each line, the res.json(data) seems to be executing twice. Can someone please correct me if I'm mistaken? Here is the content of ...

A guide on loading theme JavaScript files in Next.js

I am planning to incorporate a theme from themeforest into Next.js Despite my attempts, I encountered issues with loading jquery core and certain plugins in Nextjs. import { useEffect } from "react" import { SessionProvider } from "next-aut ...