Reactivity in Vue.js powered by ES6 classes

I am attempting to create a computed property in Vue.js that is associated with an ES6 class. Here is an example of my Vue instance setup:

...
props: ['customClass'],
computed: {
    localClass: {
         get() {
             return this.customClass
         },
         set (value) {
             console.log("changed")
         }
     }
 }
 ...

This is the structure of my class:

class CustomClass {
    constructor () {
        this.selected = false
    }
}

When I try to modify the selected property like this:

this.localClass.selected = true

The setter function is not being triggered, and it seems like the reactivity has been lost. This behavior is confusing to me.

I have also attempted:

Vue.set(this.localClass, 'selected', true)

Although I pass customClass as a prop, even creating a new instance directly in the component does not change the outcome.

I searched through the Vue.js documentation but did not find any specific section addressing reactivity issues with ES6 classes. Can anyone offer insight on why this might be happening and how to ensure my class remains reactive?

Thank you in advance

Answer №1

When you set a computed property like myComputedProperty, it gets triggered every time you assign a value to that property (e.g.

this.myComputedProperty = {something: 'else'}
.

If you're looking for something different, you might need a watcher with deep: true. Here's an example:

watch: {
  localClass: {
    deep: true,
    handler() {
      out.innerHTML += "watched!";
    }
  }
},

Check out the demo below.

class CustomClass {
  constructor() {
    this.selected = false
  }
}
Vue.component('custom', {
  template: '#custom',
  props: ['customClass'],
  computed: {
    localClass: {
      get() {
        return this.customClass
      },
      set(value) {
        out.innerHTML += "changed!\n";
      }
    }
  },
  watch: {
    localClass: {
      deep: true,
      handler() {
        out.innerHTML += "watched!\n";
      }
    }
  },
  methods: {
    assignToSelected() {
      this.localClass.selected = true
    },
    assignToLocalClass() {
      this.localClass = {
        selected: true
      }
    }
  }
});
new Vue({
  el: '#app',
  data: {
    test: new CustomClass()
  },
})
#out { background: black; color: gray; }
span { font-size: x-small; font-family: verdana }
<script src="https://unpkg.com/vue"></script>

<template id="custom">
  <div>
    {{ localClass }}
    <br>
    <button @click="assignToSelected">assignToSelected</button>
    <span>Note: will trigger "watched!" just once, because, since the value is hardcoded in the method (see code) subsequent clicks won't modify the value.</span>
    <br><br>
    <button @click="assignToLocalClass">assignToLocalClass</button>
    <span>Note: assignToLocalClass() will trigger the computed setter, but wont trigger the watcher because the computed setter currently sets nothing, so nothing changed for the watcher to trigger.</span>
  </div>
</template>

<div id="app">
  <custom :custom-class="test"></custom>
</div>

<pre id="out"></pre>

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

Unable to make calls to functions within my JQuery prototype class

When it comes to setting up the behavior for my content_item elements, I use the following approach: $.fn.createContentItem = function() { $(this).selectItem = function() { $(".content_item").removeClass("selected"); $ ...

Troubleshooting Next.js server actions with ESLint error detection

I encountered eslint errors while developing a basic server component with server action: // /app/search/page.tsx export default function Search() { async function updateResults(formData: FormData) { "use server"; await new Promise((r ...

Getting console data in AngularJS can be achieved by using the console.log()

This log in the console is functioning correctly. Is there a way to retrieve this information for the HTML? ProductController.js $scope.selectedProduct = function(product) { console.log(product.post_title); console.log(product.ID); console.l ...

What is the best way to define these variables at a global scope within my controller?

In my controller (NodeJS/Express), I have 10 routes that all use the same variables 'startDate' and 'endDate'. Is there a way to declare these globally so they don't need to be repeated in each route? Currently, my code checks if ...

Error: The specified function in the schema is not valid for the current operation mode

I'm facing an issue with validating a material ui form using Formik and Yup. The error keeps popping up. This is the schema I imported from another file: export const validationSchema = Yup.object({ email: Yup.string() .email('Invalid Ema ...

What could be the reason for the jQuery not displaying JSON data in the console log?

When I put this code into a file named test.html: <html> <head> <title>Test</title> </head> <body> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"& ...

Loading Angular.js scripts into the webpage

My app is built using the MEAN stack. When a user visits the URL: http://localhost:3000/edit/0 Where 0 represents a record id. Initially, it seems like everything should work fine, but I am facing an issue where my scripts are not loading in the edit.js ...

What is the best way in Angular to focus on an input field using its name, model, or id?

My goal is to create a form where, upon leaving field one (blur), the system will check if the data inputted is the word "test". If the data does not contain this word, I want the focus to return to field 1. <form name='yourForm' novalidate n ...

Looking to display database information using javascript

Currently, I am working on a project involving PHP code where I retrieve variables from an input and utilize AJAX. Here is the code snippet: $.ajax({ type: "GET", url: "controller/appointment/src_agenda.php", data: { function: "professional", ...

Calculating a Price Quote

I have created a dynamic quote calculator for a Next.js project that allows users to calculate prices based on word count and selected languages. Currently, the price is calculated using a fixed rate of 0.05 per word. 'use client'; import { useS ...

Learn the process of updating a nested document within an array in MongoDB

I have a data structure as shown below: { "name":"xxxxxx", "list":[ { "listname":"XXXXX1", "card":[ { "title":"xxxxxx", "descip":"xxxxxxx ...

When displaying a collection of components, clicking a button will always select the most recent element in the array

Can you explain why this code won't work in a React environment? Every time the button is clicked, it picks up the value "name" from the last element in the array. In this example, the dialog will always display the name "John2". import React from "r ...

Query MySQL and automatically populate form fields with the data retrieved after the user triggers an "onexit" or "onsubmit" event, all without having to reload the page,

Seeking a way to auto-fill form fields with data from MySQL database. The goal is to input a value in a text field, search the database matching that value, and populate the remaining form fields without having to navigate away from the page. If anyone h ...

Having trouble getting gulp set up and running with npm?

I am currently in the process of setting up gulp using npm in order to execute my project. Based on my understanding, all I need to do is enter "npm install gulp" in the command line at the location of my project like this : https://i.stack.imgur.com/hPU ...

Discovering the absent number within a cyclical array

Looking to find the missing number between two arrays in a cyclical manner using either Javascript or jQuery. It's easy to find all missing numbers, but I specifically need to identify the single missing number within the range of the second array whi ...

Leveraging Vue js components while utilizing it from a content delivery network (CDN

I'm attempting to utilize the ButtonCounter component as a demonstration (source: https://vuejs.org/guide/essentials/component-basics.html#defining-a-component), but I am facing difficulties in getting it to function properly. I am utilizing Vue.js 3 ...

Using Firebase Authentication in Next.js with Server-Side Components

As I explore how to implement authentication using Firebase in my Next.js app, one thing that stands out is the need to initialize Firebase with our configuration details (apiKey, etc.). The concern I have is when using any Firebase function from a client ...

What crucial element is absent from my array.map function?

I have successfully implemented a table with v-for in my code (snippet provided). However, I am now trying to use Array.map to map one array to another. My goal is to display colors instead of numbers in the first column labeled as networkTeam.source. I at ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

Organizing pictures by category

I am currently working on creating an interactive image gallery with sorting options based on different categories such as land, sea, animals, and more. I have created a small example to demonstrate my concept. My objective: is to allow users to select a ...