Retrieving Vue data from parent components in a nested getter/setter context

<template>
  <div id="app">
    {{ foo.bar }}
    <button @click="meaning++">click</button> <!--not reactive-->
    <button @click="foo.bar++">click2</button>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";

@Component
export default class App extends Vue {
  private meaning = 42;

  private foo = {
    that:this,
    get bar() {
      return this.that.meaning;
    },
    set bar(value) {
      this.that.meaning = value;
    },
  };

  created() {
    console.log(this); // VueComponent {}
    console.log(this.foo.that); // App {}
    console.log(this === this.foo.that); // false
  }
}
</script>

I need to establish a connection between foo.bar and meaning, which is a top-level data field. The initial workaround involves saving this (the Vue option instance) in that. However, the issue arises when this refers to the VueComponent instance instead of this.foo.that.meaning during runtime.

Another challenge is that the above code snippet causes vue-devtools to malfunction within Chrome, as it attempts to invoke Object.keys() on instance._data, which is null.

What is the correct method for linking foo.bar to meaning? The logic within those getter and setter functions may be complex.

Answer №1

Update:

After realizing that referencing `this` in the VueComponent can only be done at runtime, I devised a somewhat unconventional workaround:

<template>
  <div id="app">
    {{ foo.bar }} 
    <button @click="meaning++">click</button>  <!-- now reactive! -->
    <button @click="foo.bar++">click2</button>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";

@Component
export default class App extends Vue {
  private meaning = 42;

  private foo = {
    that: {meaning:42} as any, // initialize with exact same literal value here
    get bar() {
        return this.that.meaning;
    },
    set bar(value) {
      this.that.meaning = value;
    },
  };

  created() {
    this.foo.that = this;
    console.log(this); // VueComponent
    console.log(this.foo.that); // VueComponent
    console.log(this === this.foo.that); // true
  }
}
</script>

Original solution:

If you are encountering a similar issue, I have come to the realization that

it's not feasible to reference external data within inner object data in the Vue configuration instance.

This is because the VueComponent instance can only be accessed at runtime, but setting that:this in the constructor of the Vue config class is necessary before VueComponent instantiation. Therefore, Vue's reactive system won't have an opportunity to resolve the reference in that.

My advice (based on my experience) is simply do not attempt this. Dependencies must always take precedence over dependents, and you should avoid using foo as the namespace for bar.

Elevating bar to the top level is the way to go.

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

Enhance your map by incorporating an overlay with ngx-openlayers

Currently, I am trying to implement zoom-in and zoom-out buttons on an OpenLayers map. I attempted to use the overlay method but encountered an error. Here is the code snippet for reference: zoom_button = document.getElementById('zoom') zo ...

Is it possible to pass a variable from an Axios Response in the Composition API up to the root level?

I need to fetch the headings array from an axios.get call and utilize it at the root level within my Vue component. However, when I attempt to return it, I encounter this error: ReferenceError: headings is not defined Here is the script element in my Vue3 ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

Tips for relocating the indicators of a react-material-ui-carousel

I am working with a carousel and dots indicators, but I want to move the indicators from the bottom to the circular position as shown in the image below. I attempted using a negative margin-top, but the indicators ended up being hidden. Is there another ...

Ways to initiate animation using CSS when the page loads

Is there a way to initialize the counter on page load? Even though I was successful in making it start on hover, I couldn't figure out how to make it work when the page loads. Here is the JavaScript code: var root = document.querySelector(':root ...

What is the best way to replicate a synchronous ajax call? (mimicking synchronous behavior with asynchronous methods)

Given that a "native" synchronous ajax call can block the user interface of the browser, it may not be suitable for many real-world scenarios (including mine). I am curious to know if there is a way to mimic a synchronous (blocking) ajax call using an asy ...

Tips for displaying diverse content in a DIV container when users click on various sections of an image

Apologies for the unclear title, but I'm struggling to explain my technical goal using jargon. The basic concept is this: there will be an image on the webpage, and when a user clicks on a specific area of the image, relevant information will appear ...

Deactivate certain days in Material UI calendar component within a React application

Currently, my DatePicker component in React js is utilizing material-ui v0.20.0. <Field name='appointmentDate' label="Select Date" component={this.renderDatePicker} /> renderDatePicker = ({ input, label, meta: { touched, error ...

Discover instances of a string within an array using JQuery

I am currently exploring how to locate occurrences of a specific string within an array on the client side. The examples provided on the JQuery Docs all seem focused on number comparisons, which isn't quite what I need. Essentially, I'm attempti ...

Using TypeScript to define a constant array as a type

I've hit a roadblock in my typescript project while trying to define a suitable type. Here's the setup: Within my project, I have the following constant: export const PROPERTYOPTIONS = [ { value: "tag", label: "Tag" }, { ...

Is it possible to share a Vue.js component by "transferring" it rather than duplicating it?

In my comment system project using Vue.js, I have over 300 comments to manage. Each comment has an admin section that appears when the cursor hovers over it. Duplicating the admin section component for each comment is not ideal as it creates unnecessary l ...

Angular2 - Access to fetch at 'https://example.com' from

Requesting some guidance on integrating the forecast API into my angular2 application. Currently facing a Cross-Origin Error while attempting to access the API. Any suggestions on resolving this issue? search(latitude: any, longitude: any){ consol ...

The saving function of the Jquery camera is not working properly and does not store the

I seem to be having an issue when using the jquery camera in "save" mode. Despite trying to call the url in "webcam.save" manually, it doesn't seem to have any effect. It appears that the jquery camera plugin may not be functioning as intended. Any su ...

Error: Unrecognized action type in Vuex

I've been encountering some major issues with vuex lately. For some reason, getters, actions, and mutations are not being recognized. In the code snippet below, although fetchFacilities is working fine, addFacility is throwing an error: [vuex] unknown ...

Exploring Angular 5's *ngFor directive with an array of objects

Here is the data I am working with: Initial set of data: var input = [ {ru: "R201", area: "211", unit: "211"}, {ru: "R201", area: "212", unit: "NONE"}, {ru: "R201", area: "HCC", unit: "NONE"}]; Desired result data: var result = [ {area: ...

The default route in Laravel is not functioning properly in conjunction with Vue.js

I am currently working on a single page application with Laravel and Vue, but I'm facing an issue where the index component is not loading upon initial page load. In my web.php file: Route::get('{any}', function () { return view('welco ...

What would be the best way to display a label once the zoom level exceeds a certain threshold in Leaflet?

As someone new to the Leaflet library and JavaScript in general, I'm currently facing a challenge with showing/hiding a leaflet label based on the zoom level. The markers are within a 'cluster' layer loaded via AJAX callback, and I bind the ...

How to use TypeScript variables in React applications

In my current project, I am attempting to customize a Fabric JS component (Dropdown) using styled-components within a React component. The specific CSS class names are defined in a file located at office-ui-fabric-react/lib/components/Dropdown/Dropdown.sc ...

MongoDB Integration of Collections - No Data Population

Having trouble merging a client and an account collection. When I use res.send(client), only the account id's are returned. Unsure how to include account information in clients. Have seen one to many solutions, but struggling with this two-way relati ...

Transferring Information Between Components

After logging into my login component, I want to pass data to my navbar component but unfortunately, my navbar content does not update. The navbar component is located in the app-module while the login component is in a separate module. I attempted to us ...