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

Guide to sequentially playing multiple video objects with buffering

As I work on developing a reference player application that utilizes node.js, javascript, and HTML5, I have encountered an issue. Currently, my player successfully loads a single video and generates diagnostic data from it. However, I am striving to enhanc ...

Ways to display an error notification alongside another message

I have set up a validation directive that requires users to check a box. If the checkbox is left unchecked, an error message will be displayed. However, I am facing an issue where the message overlaps with the checkbox text. https://i.sstatic.net/iTKoo.jp ...

Transforming this Rails form into an Ajax/JavaScript/jQuery format will eliminate the need for submission

I have developed a form in Rails that computes the Gross Profit Margin Percentage based on an input of Price. When a user selects the relevant product on the form and enters a price in the 'deal_price' field. A callback is triggered to retrieve ...

Updating user data when logged in on multiple browsers can be tricky. Here's how to make sure that

I am currently using the express-session middleware to store user sessions in a Mongo collection. What is the most effective way to update all user sessions when changes are made from one session? For instance, if a user updates their email in session A, ...

Developing ES6 modules in C++ using Node.js

Here is a previous example showcasing how to create a Node.js addon in C++: https://nodejs.org/api/addons.html You can use node-gyp to build it into a common JS module, which works well with the 'require' function. However, when trying to impo ...

My goal is to utilize React JS to generate a table by sending the values through props using an array of objects

I have experience building tables as part of various projects, but I am facing challenges creating a table based on the provided format for this specific project. My goal is to utilize the RecordTable Component, render the table component, pass the row com ...

I believe this solution is functional, but it seems to undermine the intention of utilizing a framework

Having just started with vue and js, I recently put together a photo gallery. I'm looking to reduce the opacity of selected photos and then reset it when switching between photos. The current code works fine, but I believe there could be a better way ...

Opinions on crafting a new gadget?

I will only provide each website interested in my widget with the code to copy and paste once. It is crucial that the code is future-proof. After much consideration, this is the widget code I have developed: <script type="text/javascript" src="http:/ ...

Animating with JQuery utilizing a dynamic attribute

We are facing a challenge with animating multiple divs that share the same class name and have different attribute values: <div class="chart-bar" style="width:10%;" bar-width="100%"></div> <div class="chart-bar" style="width:10%;" bar-wid ...

Unable to change the color of InputBase component's placeholder in React.js

I've been attempting to modify the color of the placeholder in an inputbase. I came across several methods online and tried implementing them, but none have been successful. Below are the codes I have tried. <InputBase id="input-id&quo ...

What could be causing the "ERROR TypeError: Cannot read property 'length' of undefined" message to occur with a defined array in my code?

Even though I defined and initialized my array twice, I am encountering a runtime error: "ERROR TypeError: Cannot read property 'length' of undefined." I have double-checked the definition of the array in my code, but Angular seems to be playing ...

`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look. For example: If the headerStyle member of the service is set to dark ...

Storing a reference within another reference can diminish its reactivity

I'm encountering an issue with nested refs. Whenever I try to access the inner refs, I only receive back the values instead of the reactive variables. My situation involves a Pinia store, but I've simplified it down to the essential components. ...

Embed a Vaadin component within an element dynamically generated by a Javascript component

I am currently designing a Vaadin application and working on a custom Javascript component, which is a subclass of AbstractJavascriptComponent. This component uses jQuery to generate a table-like structure. In certain scenarios, users should be able to in ...

What is the syntax for declaring a boolean or object type?

Is it possible to create a variable in TypeScript that can hold either true/false or an object of booleans? I'm still learning TS and would like some input on this syntax. variableA: { a: boolean, b: boolean } | boolean I found a workaround for now, ...

Tips for halting click propagation in VueJS

My dilemma lies within a recursive list (tree) where each element contains a @click="sayHello(el.id)". The challenge arises due to the nested structure of the list, such as: list-element-0-01 ├──list-el-1-01 │ └──list-el-2-01 └──list ...

Scrolling vertically using window.open functionality

I am trying to open a pop-up window using window.open. I would like the scrollbars to appear only if necessary. Unfortunately, in Safari, the scrollbars do not show up unless I include scrollbars=1 in the code. However, this also causes horizontal scrollb ...

What is the most efficient way to use a for loop with JavaScript querySelectorAll to move multiple images?

I'm trying to move multiple images by defining each one with a for loop. Below is the code I have: var elem = document.querySelectorAll(".yikama"); var el; for (i = 0; i < elem.length; i++) { var el = elem[i] el.addEventListener(& ...

Is it possible to use function declaration and function expression interchangeably?

As I dive into learning about functions in Javascript, one thing that's causing confusion for me is the difference between function declaration and function expression. For example, if we take a look at this code snippet: function callFunction(fn) { ...

The catch all route in Next.js seems to be malfunctioning when paired with the getStaticPaths function

Why is the Next.js catch all route not working as expected with the getStaticPaths function? The documentation states that I should be able to navigate to both t/a.cat and t/a.cat/a.id, but it only seems to work for the latter. What could be causing this ...