Getting it Right: Harnessing Computed Properties in VueJS

How can I organize my data effectively when dealing with computed properties that have different values?

computed: {
  totalCoin() {
    const state = this.$store.state.ApiState.totalCoin
    let val
    if (state === 0) {
      val = 0
    } else if (state === null) {
      val = undefined
    } else {
      val = state
    }
   return val
  },
  totalGem() {
    const state = this.$store.state.ApiState.totalGem
    let val
    if (state === 0) {
      val = 0
    } else if (state === null) {
      val = undefined
    } else {
      val = state
    }
   return val
  }
  repeatedly...
}

Note: All result values will be returned from VueX to a component using computed properties

getToken() {
  return this.$store.state.userToken
}

Is there a more readable way of organizing this code for better clarity?

Answer №1

  • In my opinion, separating getters in the Vuex file is a good practice.
const getters = {
    getCoinTotal(state){
        return state.coinTotal == null? undefined : state.coinTotal;
    },
    getGemTotal(state){
        return state.gemTotal == null? undefined : state.gemTotal;
    }
}
  • After defining the getters, you can easily link them to your Vue component using mapGetters:
import { mapGetters } from 'vuex';

export default {
  // ...
  computed: {
    // connect `this.coinTotal` to `this.$store.getters.getCoinTotal`
    ...mapGetters({coinTotal: 'getCoinTotal', gemTotal: 'getGemTotal'})
  }
}

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

Third Party Embedded Video requiring SSL Certificate

I am currently facing an issue where I am trying to embed videos from a website that does not have an SSL certificate. This is causing my own website to appear insecure when the page with the embedded video loads, despite the fact that my website has its ...

Navigating a complex web: Djikstra algorithm applied to a multigraph

Encountering an issue while implementing Dijkstra's algorithm on a multigraph. The graph consists of nodes representing stops with information and connections to other stops (edges). However, the challenge arises when there are multiple bus options be ...

Utilizing arrays in JavaScript alongside jQuery's methods such as $.inArray() and .splice()

I am currently dealing with an array that is limited to containing 12 values, ranging from 1 to 12. These values can be in any order within the array. My task is to iterate through the array and identify the first unused value, assigning it to a variable. ...

What is the best way to automatically populate additional autocomplete options after selecting certain data, and include new data if it is not already present?

Is it possible to automatically populate the other Autocomplete fields based on matching first and last names? I am encountering scenarios where multiple individuals share similar first or last names but have different addresses. In addition, I would like ...

Sinon - a spy that can intercept *all* property accesses on an object

I have a function that looks something like this: import {someLibraryMethod} from 'someLibrary'; function setFullWidth(el) { someLibraryMethod(el); el.setAttribute('width', '100%'); } To test this function, I am utilizi ...

Can a json file be generated and saved using PhoneGap's file system and JavaScript?

Is it feasible to gather user data and save it as a JSON file for JavaScript to retrieve each time the user interacts with the application? ...

ReactJS: Error in syntax detected in src/App.js at line 16, column 6. This token is unexpected

Just starting out with reactjs and encountered a simple example in a tutorial. Ran into a syntax error when trying to return html tags. Below is the error that popped up: ./src/App.js Syntax error: C:/Users/react-tutotial/src/App.js: Unexpected token ...

Is there a solution for passing multiseries data in JSON that works with AnyChart in ReactJS since the standard method is not functioning correctly?

I need help implementing a column chart using AnyChart in react with multi-series data. Below is a sample JSON structure that I am having trouble passing to the chart. const multiSeriesSettings = { width: 800, height: 600, type: "column", ...

The use of history.pushState in Chrome triggers a request for the favicon

Code : var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname +"?"+ queryStr; window.history.pushState({path:newurl},'',newurl) Current issue : There is a problem where each time wind ...

The issue with fancybox links not functioning properly within ajax content

I'm looking to constantly update a specific section on my website using ajax, jquery, and php. Upon the initial page load, a javascript function is triggered to display the content of that section. Subsequently, json is utilized to check for any new ...

ASP.net is encountering difficulty locating a specific JavaScript function

Seeking assistance to comprehend the issue, I have devoted countless hours scouring Google for a resolution. Current tools in use: ASP.NET entity framework Within a view, the following code is utilized: <button type="button" id="btnGraf ...

Attempt to efficiently register components automatically on a global scale in Vue by utilizing the powerful combination of Laravel-Mix and Webpack

In my previous projects with Vue, which were based in a Laravel-Mix/Webpack runtime environment, I used to individually register components and views as needed. This was done by importing them and extending Vue: import BaseButton from './components/Ba ...

Rediscovering the magic of Vue.js HTML parsing

I have a template with Vue.js attributes and bindings. For instance: <a v-on:click="loadAdditionalBusinesses()" v-if="!additionalBusinesses" class="btn btn-info btn-sm btn-block">Load additional profiles</a> <div v-if="addi ...

Identify and emphasize fields that contain identical, non-empty values

I am attempting to compare the values of textboxes and highlight them if they are the same, excluding any textboxes that are empty. Feel free to view an example on this JSFiddle link: http://jsfiddle.net/qjqa1et2/61/ Below is the jQuery code I am current ...

The onsubmit function is not successfully executing the JavaScript function

This code contains a form for creating a new user login. Upon pressing the 'continue' button, it is supposed to call the 'validateForm()' function which checks the values entered in the form. However, even when there are errors such as ...

executing concurrent npm tasks on a Windows operating system

After setting up an npm parallel script in my package.json, I noticed that it works smoothly on a mac but encounters issues when run on windows: "myScript": "nodemon ./server.js & cross-env NODE_ENV=development webpack-dev-server" However, when the s ...

`What is the best way to adjust scroll position using jQuery?`

After encountering a similar issue with locking the vertical scroll while opening a mobile menu on a website I'm working on, I came across a potential solution HERE. However, despite trying to implement it, I haven't been successful. The main pro ...

Unable to launch React Native project on emulator now

Something seems off with my App as it won't start up on my AS Emulator. Everything was running smoothly yesterday, but today it's not working - possibly due to me moving the npm and npm-cache folders, although they are configured correctly with n ...

Request data from another $http request in a different file using synchronous calling

Looking to extract a URL from a JSON file and pass it to another JavaScript file that makes an HTTP GET request to execute the URL. This setup involves using one service within another service file to retrieve data. However, upon running the process, the f ...

Angular: When $scope variable is modified, a blank page issue arises

In my Angular application, I have a template called viewAll.html that is displayed after clicking on a link. This template fetches data via AJAX using scope variables. However, I encountered an issue where updating these scope variables through AJAX cause ...