Tips on handling a Vue computed property

I am struggling to dispatch an object that is created within a computed property in vue.js. Being fairly new to this framework, I can't seem to make it work.

My goal is to dispatch the object named "updateObject" to the vuex-store. I have tried using setters without success. I believe that if I can set the "varia" object to the same value as "updateObject", then maybe I could dispatch it? Any help would be greatly appreciated.

Below is the code snippet:

<template>
  <div class="detail">
     <b-row align-v="center"><b-button variant="success" @click="submit()">submit</b-button></b-row>
     // some more code...
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data () {
    return {
      subID: '',
      res: '',
      showAlert: true,
      varia: null
    }
  },
  computed: {
    ...mapState([
      'FA',
      'Main',
      'Sub',
      'layouttype'
    ]),
    getVariable: function (Sub, layouttype) {
      const subID = this.layouttype.sub_id
      var filterObj = this.Sub.filter(function (e) {
        return e.sub_id === subID
      })
      console.log(filterObj)
      return filterObj
    },
    updateObject: {
      // getterfunction

      get: function () {
        var len = this.getVariable.length
        var res = []
        for (var i = 0; i < len; i++) {
          if (i in this.getVariable) {
            var val = this.getVariable[i].variable
            res.push(val)
          }
        }
        console.log(res)
        var ergebnis = {}

        res.forEach(key => {
          if (this.FA[key]) {
            ergebnis[key] = this.FA[key]
          }
        })

        return ergebnis
      },
      // setterfunction
      set: function (value) {
        this.varia = value
      }
    }
  },
  methods: {
    submit () {
      this.$store.dispatch('sendData', this.ergebnis)
    }
  }
}
</script>

It's indicating that "this.ergebnis" is undefined.

Answer №1

If you want to access "ergebnis" globally, you can declare it as a global variable under the data property like this:

export default {
  data () {
    return {
      subID: '',
      res: '',
      showAlert: true,
      varia: null,
      ergebnis : {}
    }
  },
  computed: {
    ...mapState([
      'FA',
      'Main',
      'Sub',
      'layouttype'
    ]),
    getVariable: function (Sub, layouttype) {
      const subID = this.layouttype.sub_id
      var filterObj = this.Sub.filter(function (e) {
        return e.sub_id === subID
      })
      console.log(filterObj)
      return filterObj
    },
    updateObject: {
      // getterfunction
      get: function () {
        var len = this.getVariable.length
        var res = []
        for (var i = 0; i < len; i++) {
          if (i in this.getVariable) {
            var val = this.getVariable[i].variable
            res.push(val)
          }
        }
        console.log(res)

        res.forEach(key => {
          if (this.FA[key]) {
            this.ergebnis[key] = this.FA[key]
          }
        })

        return this.ergebnis
      },
      // setterfunction
      set: function (value) {
        this.varia = value
      }
    }
  },
  methods: {
    submit () {
      this.$store.dispatch('sendData', this.ergebnis)
    }
  }
}

By following these steps, you can now access the "ergebnis" variable throughout your code.

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

Using the axios response to assign data object in VueJS

When making an API call, I am receiving an expected error. While I am able to log the error message in the console, I am encountering issues trying to set a vuejs data variable with the response. Can anyone point out what I might be doing incorrectly? ...

Displaying various Vue components within Laravel 6.x

After diving into Laravel and Vue, I managed to put together a navigation component as well as an article component. The problem I'm facing is that although my navigation vue component is visible, the article component seems to be missing. Reviewing ...

Guidelines for attaining seamless motion animation utilizing devicemotion rotationRate information

I am utilizing the rotationRate data obtained from the devicemotion eventListener to manipulate a three.js scene by tilting. The scene does respond to the data accurately in terms of angle adjustments, but it produces an unsmooth motion effect. Is there a ...

Access information from JSON file

Looking to extract data from an external JSON file and store it in a JavaScript array for manipulation? Here is a snippet of the JSON file for reference: "Country":[ { "Country_Name":"India", "Country_Details":[ { ...

Locate a specific sequence of characters within an array of objects using JavaScript

I am working with an array of objects, where each object contains a string value. My task is to search for a specific substring within the string. [ { "link": "https://www.sec.gov/Archives/edgar/data/1702510/000170251022000084/00 ...

Iterate over an array in JavaScript and include the elements as parameters in an SQL query

Can I set an SQL string to a variable in JavaScript and populate part of it by looping through an array? Here is the initial SQL: var tag = ["fun", "beach", "sun"]; var sql = "SELECT * FROM myTable " +"WHERE id > 5" //... // L ...

Unable to Define Headers in Fetch GET Call

My current struggle involves sending a GET Request from the browser to my backend (which uses node + express). However, I am encountering issues with setting the headers properly. Below is the code snippet from the frontend: let accessToken = localStorage ...

JSdom, automation, web scraping, handling dynamic iframes

I am currently in the process of automating my tasks on the website provided at the link below: I need to fill out forms and submit them automatically. So far, I have been successful in automating using Greasemonkey and I am now considering switching to ...

What is the solution to the question: "Hey there, time traveler. We are currently in an era where CSS prefixes are no longer necessary, thanks to the advances in prefix-less CSS

I'm having an issue in my Next.JS app with importing my stylesheet in _app.js. Here is how I currently import it: import '../public/css/Index.css'; The content of Index.css looks like this: .index-container { margin: 20px auto 0; } Wha ...

When is it necessary to use JSON.parse(JSON.stringify()) with a Buffer object?

I am currently working with Buffer objects in my existing code. let dataObject = JSON.parse(JSON.stringify(data)); At first glance, it seems like the above code is redundant and doesn't achieve much. However, replacing it with: let dataObject = data; ...

Session is required for req.flash() function in node.js to work properly

I recently started working with Node.js and I'm encountering an issue with sessions. I developed a simple application and tried to run it locally, but ran into some errors. Below are the details of my code along with the error messages: BAPS.js (app. ...

Attach an event listener to a class, then use the removeEventListener method to detach the listener and eliminate any remaining references, ensuring proper functionality of the

When creating a class in JavaScript, a normal function returns the class object. However, events return the event object and the class object is lost: function class(a){ this.name=a; document.addEventListener('click',this.click,false); xhr.add ...

Zingchart encounters issues when attempting to plot a CSV file containing over 10 columns

Situation: I want to create a Zingchart graph from a CSV file containing 37 columns. The header in the CSV file will be used as the legend for the graph. Issue: When I define less than 10 elements in the header (including the X-axis name), everything wo ...

The functionality of Dnd-kit nested is functioning properly, however, one specific component is unfortunately

Currently, I am dealing with a two-dimensional array that results in two nested dnd-kit drag and drop fields. The nested dnd functions correctly; however, the first one sorts items when moved without any animations (even when moving my div). Below is the ...

What are the best practices for iterating through asynchronous generator functions?

Suppose we have an asynchronous generator: exports.asyncGen = async function* (items) { for (const item of items) { const result = await someAsyncFunc(item) yield result; } } Can we apply mapping to this generator? In essence, I am attempting ...

What is the best way to reset the state in vuex store?

My vuex store contains a lot of data. Is there an efficient way to clear all the state data at once, rather than having to manually set each item to null? ...

Bizarre String Behavior in jQuery JSON Through Ajax Request

Something unusual is occurring: whenever I try to send the string "??" to the server using AJAX $.ajax({ type: 'POST', url: path, dataType: 'json', data: JSON.stringify({ text: "??" }) }); it consistently results in send ...

React Native formInput Component with Underline Decoration

Utilizing the FormInput element in React Native Elements, I have observed a line underneath each FormInput component. Interestingly, one line appears fainter than the other. This is how the form looks: <View style={styles.container}> ...

What could be the reason for the component bindings being undefined within the controller?

I'm currently working on a basic angular component. I have set up a parameter as a binding and managed to display its value on the screen successfully. The parameter displays correctly, but when I try to access it within the controller, it shows undef ...

The process of rendering children elements in React

I have a question about managing children components in React. While there are resources available explaining this concept, I believe a more detailed explanation would be helpful. Let's consider the structure of my React component tree, which looks l ...