VueJS ensures that instance properties are reactive

Currently, I am in the process of developing a VueJS plugin that utilizes instance properties. I find myself needing to reintroduce some reactive values back into VueJS.

After conducting my research:

I have been struggling to grasp the concept behind Object.defineProperty(). My search led me to explore vuex getters initialization as it shares similarities with my logic, however, I am still unable to fully comprehend its functionality.

Illustrative Example :

The following is a code snippet within the prototype of a VueJS file, main.js :

Vue.prototype.$ajax = {
  loading: false,
  isLoading () {
    return this.loading
  }
}

Moving on to accessing this from a component, component.vue :

export default {
    computed: {
      loading () {
        return this.$ajax.isLoading()
      }
    },
    created () {
      let self = this

      setInterval(() => {
        console.log(this.loading, this.$ajax.isLoading())
      }, 100)

      setTimeout (() => {
        this.$ajax.loading = true
      }, 1000)
    }
  }
}

Outcome of the Example :

Prior to the setTimeout, we observe false false (as expected), but after the execution of setTimeout, the results display false true (wherein the getter fails to reflect the modification, yet the direct accessor holds the updated value).

Do you have any suggestions for injecting reactivity into my $ajax.isLoading() method?

Answer №1

Through investigating the vuex code, I was able to discover a solution: incorporate a Vue instance within the plugin that contains your data to enable reactivity outside of it.

Here is an excerpt from the initial inquiry:

Vue.prototype.$ajax = {
  _vm: new Vue({data: {
    loading: false
  }}),
  setLoading (loading) {
    this._vm.$data.loading = loading
  },
  isLoading () {
    return this._vm.$data.loading
  }
}

I made a modification by replacing the direct accessor with this setter in my component:

this.$ajax.setLoading(true)

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

Creating a dynamic Ajax-based widget for your website: A step-by-step guide

I have a unique idea for a web widget that I want to create. This widget will need to be easily integrated into any website using javascript. It will post a form to my server, receive the data, and display the results in a small area of the host website&ap ...

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

Locate a jquery element that is within a parent element containing specific text

This is the format I currently have: <td width="270px"> <img class="bullet" border="0" valign="top" src="gray-bullet.gif"> this is the text </td> Can someone provide me with a query to specifically target the img element with the class ...

Is it possible for the Observable call in Angular 4 to function similarly to jQuery's synchronous AJAX method?

As I have a business logic function that needs to use HttpGet and I must wait for the result before continuing, jQuery's ajax can handle this easily. But I am curious if Observables have a similar feature? I was hoping for the result to be: John An ...

Is AngularJS the right choice for developing this application?

Recently, I've come to the realization that I want to dive into the world of AngularJS framework after working with jQuery for several years. I have a vision of developing an application that allows users to easily modify webpage DOM using a browser- ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

Harness the power of ng-click in conjunction with data-ng-href for a

I am attempting to create a button that takes the user to the product details while also having the ability to increase a counter using an ng-click function. <div class="row center-block save-button" > <a data-ng-href="/savings/{{saving._id}} ...

Is it possible for setTimeout to not increment the counter in node.js?

Even though the loop is executed multiple times in the Node.js program below, why does the control not exit the loop? I made sure to increment the value of i within setTimeout instead of forgetting to do i++ in the for loop. function abc () { for(var ...

Tips for managing promise rejection when generating a highland stream from a promise?

When working with [email protected] and [email protected] via typescript, the following code snippet is utilized: import * as highland from "highland"; import * as lodash from "lodash/fp"; const range = lodash.range(0, 10); const createPromise ...

Storing various property values in Vuex stateorManaging multiple property

Here is a demo link that I would like to share: https://codepen.io/Albvadi/pen/abdVZxO In the payload, I am trying to pass the title and class but only the class is being recognized. When I attempt to change the @click event to pass an object, the JavaSc ...

Can you explain the significance behind the error message "RangeError: Invalid status code: 0"?

Currently, I'm trying to understand the workings of express and have come up with this get method: app.get('/myendpoint', function(req, res) { var js = JSON.parse ({code: 'success', message:'Valid'}); res.status( ...

Simulating a click event on a file input using .click() method is ineffective on iOS when using Cordova framework

I am currently utilizing React to construct a web application that is wrapped with Cordova in order to function as a native app on both android and iOS platforms. The challenge I am facing specifically pertains to iOS, particularly when attempting to simul ...

Using a toolbar to insert a hyperlink for hypertext communication

My journey with Javascript and React began this week, so I'm still getting the hang of things, especially in the front end domain. In my project, there's a link button within a toolbar. The idea is to click on it, have a text box pop up where yo ...

External Submit button malfunctioning when attempting to submit two distinct forms

I'm currently working on a program to add items to the cart, and I need to include product attributes like colors and sizes in the process. However, I seem to be encountering an issue where only one form is submitted when using jQuery's submit(), ...

Identify the row containing a value of null using jQuery (functionality not performing as anticipated)

Whenever the user clicks on the GetData button, I retrieve JSON data and display it in an HTML table similar to the demo below. Demo: https://plnkr.co/edit/I4XYY6CZohf7IS6wP8dR?p=preview There are instances where the value can be null, such as the loanNu ...

Twitter typeahead not functioning properly when used in conjunction with ajax requests

I have limited experience in the frontend world and I'm currently working on getting this to function properly. $('#the-basics .typeahead').typeahead({ hint: true, highlight: true, minLength: 6 }, { source: function (query, ...

Error encountered while integrating sweetalert into Vue.js framework

Can anyone help me with importing sweetalert2 correctly to use Swal in this file only? I tried using <script src = "https://cdn.jsdelivr.net/npm/sweetalert2@9"> but it's not working as expected. What could be the issue? <script ...

Vue3 can accept a prop of type String or PropType

In my Vue3 project, I have a component that accepts a prop which can be either a string or an object. Here's how it looks: import { defineComponent } from 'vue' const Component = defineComponent({ props: { book: { type: [String, ...

"Troubleshooting: Why is the 'RectAreaLightHelper' not moving correctly in React-three-fiber

Issue Overview: I have noticed that the rectAreaLight behaves differently compared to other light helpers in my project. Despite using the "useHelper" function and placing it in the "three/examples" folder, the position of the rectAreaLight does not change ...