Creating a reactive "virtual" getter for a class in VueJS

There are two objects in my code, BlogPost and Comment, with the following structure:


class Comment {
  constructor (blogId, text) {
    this.blogId = id
    this.text = text
  }
}

class BlogPost {
  constructor (id, text) {
    this.id = id
    this.text = text
  }
  get comments () {
    return commentCollection.filter(comment => comment.blogId === this.id)
  }
}

I am looking to make the comments getter act as a reactive property. In the given vue setup...

<template>
  <div>
    <h1>The post has {{myBlogPost.comments.length}} comments</h1>
    <v-btn @click="addComment()">Add Comment</v-btn>
  </div>
</template>

<script>

export default {
  data () {
    return {
      myBlogPost: null
    }
  },
  methods: {
    let newComment = new Comment('myBlogId_0', 'This is a comment on hello world')
    commentCollection.splice(0, 0, newComment)
  },
  mounted () {
    this.myBlogPost = new BlogPost('myBlogId_0', 'Hello World')
  }
}
</script>

I want the comment count to update when a user adds a comment. How can I achieve this? Making the comment collection of BlogPost reactive doesn't seem possible since it's not a propery.

I have tried using a computed method in Vue that calls the "getter" on BlogPost, but it doesn't establish a dependency with the comments collection. Using Vue.set() also didn't yield desired results. Where should I make changes to trigger reactivity in Vue?

The only solution I can think of involves setting up a watcher on the comments collection and updating another value in data by calling the comments getter. However, this approach may become cumbersome if multiple similar situations arise within different objects. Is there a more efficient way to handle this without relying heavily on watchers and extra state in data? Thank you!

Answer №1

If you're looking for some assistance, consider the following code snippet:

<template>
  <div>
    <h1>The post currently has {{myBlogPost.comments.length}} comments</h1>
    <v-btn @click="addComment">Add Comment</v-btn>
  </div>
</template>

<script>

export default {
  data () {
    return {
      myBlogPost: {
        comments: []
      }
    }
  },
  methods: {
    addComment() {
      let newComment = new Comment('myBlogId_0', 'This is a comment on hello world')
      // Please note that commentCollection is not defined in this excerpt
      commentCollection.splice(0, 0, newComment)
      this.myBlogPost.comments.push( newComment )
    }
    // let newComment = new Comment('myBlogId_0', 'This is a comment on hello world')
    // commentCollection.splice(0, 0, newComment)
  },
  mounted () {
    this.myBlogPost = new BlogPost('myBlogId_0', 'Hello World')
  }
}
</script>

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

Retrieve an image from the database and associate it with corresponding features or news in PHP

I have retrieved a value from the database, displayed it as an image, and made it a link. So, I want that when a user clicks on the different image, they get the result from the query related to the image. I hope everyone understands. <?php // Connect ...

When you tap on the screen, the keyboard disappears and you have to hold

I have encountered an issue in my web view where I am programmatically creating an input field element using JavaScript and setting focus to it after creation. The problem is that the keyboard pops up for a split second and then closes when trying to focus ...

Vue 3 Single Page Application. When selecting, it emits the language and the contentStore does not update the content exclusively on mobile devices

My Vue 3 Single Page Application is built on Vite 4.2 and TypeScript 5.02. When I click to select a language, it emits lang.value and in the parent component App.vue, contentStore should update the content. It works flawlessly on my Linux Ubuntu desktop i ...

The object filtering process is experiencing issues due to the presence of a null value in the column

I am trying to extract object data based on a specific value from an array. While the code snippet below works well when there are no null values, it fails to work properly when encountering null values in the column. For reference, you can check out this ...

Determine the number of occurrences of specific values within a group of objects based on a

I have the following dataset: const data2 = [ { App: "testa.com", Name: "TEST A", Category: "HR", Employees: 7 }, { App: "testd.com", Name: "TEST D", Category: "DevOps", Employee ...

What is the speed of retrieving new data once it has been inserted into a firebase real-time database?

In the midst of developing my personal project using next.js, I've encountered an issue with a component that includes a getstaticprops function. This function scrapes a website and then posts the extracted data to a firebase realtime database. Howeve ...

Tips for resolving NPM high severity vulnerabilities related to pollution issues

Every time I attempt to install npm packages, I encounter the same error message indicating "3 high severity vulnerabilities." When I execute the command npm audit fix, I consistently receive this: https://i.stack.imgur.com/3oJIB.png I have attempted to ...

Interact with Datatable by clicking on the table cell or any links within the cell

When I am working with the datatable, I want to be able to determine whether a click inside the table was made on a link or a cell. <td> Here is some text - <a href="mylink.html">mylink</a> </td> Here is how I initialize my da ...

How can I retrieve an array from an object containing both a property and an array in TypeScript?

One of my objects always consists of a property and an array. When I use the console.log(obj) method to print it out, it looks like the following example: ProjectName: MyTest1 [0] { foo: 1, bar: 2} [1] { foo: 3, bar: 4} [2] { foo: 5, bar: 6} Alternat ...

The error message "React Native Redux useSelector is returning Undefined after navigation" has

After navigating to a new state, I am facing issues with accessing the updated state. Initially, I initialize my dataState in the reducer and update it using actions. On Screen 1, I successfully use this state after dispatching, but when moving to another ...

Having difficulty retrieving items from Mongoose-Node database

I am currently working with a Mongodb database that stores resume objects. These objects contain various skills information and I have set up a node-express server to query the database based on specific skills. For example, when querying for a skill like ...

The Like and increment buttons seem to be unresponsive when placed within a FlatList component

Issues with the like and increment button functionality within the FlatList Here are my constructor, increment, and like functions: constructor(props){ super(props); this.state = { count: true, count1: 0, }; } onlike = () => ...

Default value for the href property in NextJS Link is provided

Is there a default href value for Next/Link that can be used, similar to the way it is done in plain HTML like this: <a href='#' ></a> I attempted to do this with Link, but it resulted in the page reloading. Leaving it empty caused a ...

Building a solid foundation for your project with Node.js and RESTful

I need to integrate a legacy system that offers an api with rest/json queries in Delphi. I plan to consume this data and build an app using angular + nodejs. My goal is for my application (client) to only communicate with my web-server on nodejs, which wil ...

What is causing the consistent occurrences of receiving false in Angular?

findUser(id:number):boolean{ var bool :boolean =false this.companyService.query().subscribe((result)=>{ for (let i = 0; i < result.json.length; i++) { try { if( id == result.json[i].user.id) ...

Warning: Potential Infinite Loop when using Vue JS Category Filter

I developed a program that filters events based on their program and type. The program is working correctly, however, an error message stating "You may have an infinite update loop in a component render function" keeps popping up. I suspect that the issue ...

What causes the behavior of Node.js to be the way it is?

Check out this code snippet function removePrototype() { var obj = {}; for (var _i = 0, _a = Object.getOwnPropertyNames(obj.__proto__); _i < _a.length; _i++) { var prop = _a[_i]; obj[prop] = undefined; } obj.__proto__ = ...

The useEffect hook in Next.js does not trigger a re-render when the route changes

I'm currently experiencing an issue with a useEffect inside a component that is present in every component. I've implemented some authentication and redirection logic in this component, but I've noticed that when using Next.js links or the b ...

What is the process for saving an HTML document with SaveFile.js?

I'm currently implementing a save feature for my website. Utilizing the 'SaveFile.js' module from this link: 'https://github.com/eligrey/FileSaver.js/' Once the user clicks on the save button, the goal is to have the entire documen ...

What is the method for retrieving a property from an object contained within an array that is assigned to a property of another object?

How can I retrieve the name property from the subjects array within a course object? The database in use is mongodb. Modifying the course model is not an option. The course model : const mongoose = require('mongoose'); const Schema = mongoose. ...