"Encountering a Vuex syntax issue involving the localComputed function when used in conjunction with both a getter

Whenever I try to combine a Vuex local computed object with get/set and store mappings, I encounter a syntax error.

In the Vuex documentation, it shows how you can map your store methods using the object spread operator like this:

computed: {
  localComputed () { /* ... */ },
  // mix this into the outer object with the object spread operator
  ...mapState({
    // ...
  })
}

https://vuex.vuejs.org/en/state.html##object-spread-operator

You can also create computed setters like so:

computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter

I've tried creating either a computed object with get/set or using mapState/mapGetters separately, but combining them results in a syntax error (specifically, it says: expected function name after the function declarations).

computed: {
        localComputed () {
            localMethod: {
                get: function () {
                        // retrieve
                },
                set: function (newContent) {
                    // set
                }
            }
        }, ...mapState([
                           
                       ]), ...mapGetters([])

    }

Is there a way to effectively combine these two methods?

Answer №1

When defining localMethod, make sure not to nest it inside localComputed.

In the documentation, localComputed is just a placeholder name for a computed property in your component. It is not necessary to confine all your local computed properties within it.

Therefore, you can structure your code like this:

computed: {

  localComputed: {
    get: function () {
      // retrieve
    },
    set: function (newContent) {
      // set
    }
  },

  anotherLocalComputed: {
    get: function () {
      // retrieve
    },
    set: function (newContent) {
      // set
    }
  },

  ...mapState([]),

  ...mapGetters([])

}

Answer №2

Check out this functional example. I've been successfully using this method for over a year now.

// located in the utils/vuex.js file 
export const mapSetter = (state, setters = {}) => (
  Object.keys(state).reduce((acc, stateName) => {
    acc[stateName] = {
      get: state[stateName],
   };
   // ensure setter exists
   if (setters[stateName]) {
      acc[stateName].set = setters[stateName];
   }

   return acc;
 }, {})
);

Incorporate this code snippet into your component.vue file

  import { mapSetter  } from 'path/to/utils/vuex.js';
  ...

  export default {
    name: 'ComponentName',
    computed: {
      ...mapSetter(
        mapState({
          result: ({ ITEMS }) => ITEMS.result,
          total: ({ ITEMS }) => ITEMS.total,
          current: ({ ITEMS }) => ITEMS.page,
          limit: ({ ITEMS }) => ITEMS.limit,
        }),
        {
          limit(payload) {
            this.$store.dispatch({ type: TYPES.SET_LIMIT, payload });
          },
        },
      )
    },
  }

This implementation should enable v-model binding functionality.

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

Pressing a button will reset the input spinner in Bootstrap

Is there a way to reset the bootstrap input spinner by clicking a button? I attempted using document.getelementbyId().value = "0" and also tried using reset(), but neither method worked. Any suggestions on how to successfully reset it? function resetScor ...

Why is there nothing showing up on the screen?

Just diving into Three.js and might've messed up somewhere. I'm trying to generate a geometry by using coordinates and surface data from a .k file. I checked the geometry.vertices and geometry.faces, they seem fine. I even played around with the ...

Learn how to trigger a Bootstrap 4 modal simply by clicking a button on the initial page, which will then direct you to a second page where the modal is already activated

In my current project, I am working with Bootstrap 4 and I have a specific requirement to implement a modal. The modal should function in the following way: Upon clicking a button on the first .html page, I want to be redirected to a second .html page wh ...

The anchorEl state in Material UI Popper is having trouble updating

I am currently facing an issue with the Material UI popper as the anchorEl state remains stuck at null. Although Material UI provides an example using a functional component, I am working with a class-based component where the logic is quite similar. I w ...

Using the Vuex getter to populate a component with data using the v-for directive

I am currently constructing a vue2 component, utilizing a vuex store object. The structure of the component is as follows: <template> <ul id="display"> <li v-for="item in sourceData()"> {{item.id}} </li ...

The data type 'string | number | boolean' cannot be assigned to type 'undefined'. Specifically, the type 'string' is incompatible with type 'undefined'. Error code: ts(2322)

When attempting to create a partial object with specific fields from a full object that meet certain criteria, I encountered a TypeScript error message. To better explain this issue, I designed a test module to showcase the concept/problem without using ac ...

I am facing a challenging issue with React on my console and finding it difficult to resolve

Below is the code snippet from my ShoppingList.js file, ` function ShoppingList() { return ( <ul className="lmj-plant-list"> {plantList.map(({ id, cover, title, description }) => ( <PlantItem to={"/ ...

Assign a variable to the result of ajax that remains unchanged until it is specifically invoked

I am currently working on the final part of my radio script, specifically focusing on the "last song" section. My goal is to retrieve a URL from an external PHP script, play the song, and once the song ends, I want to set a global variable equal to the cur ...

The feature of Nuxt 3's tsconfig path seems to be malfunctioning when accessed from the

Take a look at my file structure below -shared --foo.ts -web-ui (nuxt project) --pages --index.vue --index.ts --tsconfig.json This is the tsconfig for my nuxt setup. { // https://v3.nuxtjs.org/concepts/typescript "exte ...

The global coordinate system is used to determine the direction of raycasting, not the local coordinate

Using the raycasting method to detect various colored strips on both sides of the track, I am able to keep my car object in position by calculating the distance. However, the issue lies in the fact that the ray always points in a constant direction in the ...

Utilizing a switch case for typing

I am working on a React component that takes in a list and a type as props. The list is an array of objects, while the type is an optional enum string. Inside this component, there is a function that uses a switch case statement to enforce a specific type ...

The fading in process seems to be missing, leaving only the fade out effect

Here's the code snippet I am using: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> function showSignUp() { $("#re ...

Transforming Several Dropdowns using jQuery, JSON, and PHP

Hey there! I'm looking to update the state depending on the country and city based on the chosen state. <label>Country:</label><br/> <select onchange="getval(this)"> <option value="">Select Country</op ...

JavaScript code that generates HTML formatted mail body

var theApp = new ActiveXObject("Outlook.Application"); var theMailItem = theApp.CreateItem(0); theMailItem.To = to; theMailItem.Subject = (subject); theMailItem.CC = carbon; theMailItem.Body = (msg); theMailItem.display(); I have a JavaScript cod ...

Vue.js Alert: Breakpoint has been set but not yet bound in Visual Studio Code

I've been facing some challenges with debugging in VS Code while working on a large Vue.js project. Despite trying different approaches for a week, I continue to encounter issues with setting breakpoints. Interestingly, the problem seems to be more pr ...

Can the parameters in a .slice() be customized within a v-for loop?

I am currently working with Laravel 8 and using blade syntax. The following code snippet is from a Vue component I created: <li class="w-3/12 md:w-auto pt-0 md:px-4 md:pt-2 md:pb-0 list-none relative" v-if="comic.item_type === 'b&ap ...

Tips for ensuring the accurate retrieval of prop values by waiting for the value to be set

Encountering an issue with the .toUpperCase() method within one of my components, resulting in the following error: TypeError: Cannot read properties of undefined (reading 'toUpperCase') This problem seems to stem from a race condition in fetc ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Switch the script: convert from jQuery to traditional JavaScript code

I've been trying to transition from using jQuery for a toggle script on my website to just using normal JavaScript in order to clean up the code. However, I'm having trouble converting the existing jQuery code into vanilla JavaScript. Here is th ...

Focus loss occurs when the state changes in a Custom Tooltip containing an MUI TextField

Currently, I am utilizing MUI and have implemented a custom Tooltip for one specific TextField within my form. The issue arises when I start typing in this particular TextField as it loses focus immediately. Consequently, the state of the value in my formD ...