Establishing a small boutique utilizing Vue.observable for property getters

I am currently importing the createStore function into a store.js file and passing an object with state properties and mutation functions as an argument, which is working well.

createStore.js

import Vue from 'vue'
 
function createStore({ state, mutations }) {
  return {
    state: Vue.observable(state),
    commit(key, ...args) {
      mutations[key](state, ...args)
    }
  }
}
 
export default createStore

store.js

import create from './createStore.js'

const store = create ({
    state: {
      counter: 0
    },
    mutations: {
      increment(state, payload){
        state.counter += payload
      }
    }
})

export default store

Now I am planning to modify the createStore function to include a getters property and utilize this in a component. For example:

CompExample.vue

computed: {
  counter() {
    return store.getters.counter
  }
}

Thank you.

Answer №1

If you want to create custom store getters (similar to Vuex's getters) based on a given getters map:

  1. Create a new object named myGetters to hold our new getters.
  2. Utilize Object.entries() on the getters object to extract its keys and values.
  3. For each key/value pair, utilize Object.defineProperty() on myGetters to define a getter that calls the value (if it's a function) with state as the argument.
function createStore({ state, mutations, getters }) {
  1️⃣
  const myGetters = {}

  if (getters) {
    2️⃣
    Object.entries(getters).forEach(([key, value]) => {
      3️⃣
      Object.defineProperty(myGetters, key, {
        get: () => typeof value === 'function' ? value(state) : value
      })
    })
  }

  return {
    //...
    getters: myGetters
  }
}

Next, configure it in the store.js file like this:

const store = createStore({
  //...
  getters: {
    counter: state => state.counter,
    half: state => state.counter / 2,
    double: state => state.counter * 2,
    square: state => Math.pow(state.counter, 2)
  }
})

example

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

Sequencing code execution correctly in Node.js

I am currently working on a website that consolidates articles based on user interests. Although I have a backend set up, I am struggling to execute the code in the correct sequence. Essentially, my database consists of MongoDB containing user informatio ...

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Synchronizing code paths that involve both ajax and non-ajax functions can be achieved by

My website features a basket functionality where users can enter an author's name and see the available books. After selecting desired books, they have the option to click on another author for more selection. The displayed list includes books by Step ...

Real-time Dropdown Updating in PHP

I apologize if this question has been addressed previously, but I have attempted a search and have not found answers in other posts. The responses I did come across did not pertain to my specific question (which mostly revolved around dropdowns fetching re ...

Updating the value of a MongoDB item two days after its creation

I've been working on a NodeJS application that stores form data in a MongoDB database collection. My goal is to implement a function that can modify certain values of the object in the database collection 48 hours after the form data is initially save ...

Dynamically changing the borders of WebGL canvases: a guide to adding and

Here is my code snippet for creating an HTML canvas: <canvas id="glCanvas" class="canvases" width="20" height="20></canvas> To set the color, I am using the following: gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); I am w ...

The console is reporting an error stating it cannot read the charCodeAt property

<script> var str=prompt('please enter a string'); var a= str.split(''); for (j=0; j<str.length; j++){ for(i=j; i<str.length; i++) { if(a[i].charCodeAt(0) > a[i+1].charCodeAt(0)) { var b= a[i]; a[i]=a[i+ ...

What is the process for extracting an object from an array?

As a newcomer to jQuery, I've encountered an issue that has me stuck. My problem lies in accessing an array within an object. Here's the structure of my object as shown during debugging: cache:object 0001-:Array[2] 0:value1, ...

JavaScript - Attempting to Add Objects to Array Unsuccessful

After seeing this question raised multiple times, I am determined to find a solution. In my current project, I am tasked with displaying a list of orders and implementing a filter by date functionality. However, I keep encountering an error when trying to ...

How can I use variables to show the second dropdown list only when a value has been selected in the first dropdown?

Is there any way I can choose a specific value from a dropdown list and based on that selection, show another dropdown list? I understand how to do it with regular words, but what if I use variable names? University Name: <select name="university" id=" ...

Whenever I navigate to a new page in my NEXTJS project, it loads an excessive number of modules

I am currently working on a small Next.js project and facing an issue where the initial load time is excessively long. Whenever I click on a link to navigate to a page like home/product/[slug], it takes around 12 seconds to load due to compiling over 2000 ...

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

Ways to engage with a fixed html page generated by an Express router?

Let me start by mentioning that I am relatively new to working with NodeJs. Currently, I am dealing with a situation where I need to render a static HTML web page (which includes JavaScript code) as a response to a post request. Below is the relevant snipp ...

Having trouble simulating JavaScript Math.random in Jest?

Math.random() seems to always return random values instead of the mocked ones. script.test.js jest.spyOn(global.Math, "random").mockReturnValue(0.123456789); const html = fs.readFileSync(path.resolve(__dirname, "./script.html"), " ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

Tips for preventing a table from showing up while scrolling unnecessarily when utilizing a heading with the CSS position property set to 'sticky'

Currently, I am facing an issue with creating a sticky header for my table. The problem arises when the header of the table has rounded edges (top right and top left) along with a box-shadow applied to the entire table. As the user scrolls through the tabl ...

Maximizing Efficiency: Utilizing a Single jQuery Function to Retrieve Specific Values

I have a webpage with select menus for choosing user type, minimum age, and maximum age. I want to select options and send values as an object array to ajax. Initially, the getAjax function is working when the page loads. However, it stops working when I c ...

Tracking the number of form submissions on a PHP website

I am looking to add a counter feature to my website where every time a form is submitted, the count increases for all visitors. The starting number will be 0 and each form submission will increment the count. While I can manage the count using JS/jQuery w ...

Unable to redirect Firebase Hosting root to a Cloud Function successfully

Currently I am utilizing Firebase Hosting along with a Firebase.json file that is configured to direct all traffic towards a cloud function (prerender) responsible for populating meta and og tags for SEO purposes. { "hosting": { "public": "dist/pr ...

Divide JSON information into distinct pieces utilizing JQuery

$.ajax({ type: 'POST', url: 'url', data: val, async: false, dataType: 'json', success: function (max) { console.log(max.origin); } ...