How can VueJS manipulate state with Mutation?

I have set up a Vuex Store that returns data on headers and desserts. The desserts object includes a property called display, which is initially set to false. In my project, I am using a component called Row within another component named Table. The Row component accepts props such as Name and Display, where the Display prop comes from the Vuex store's desserts data. I'm attempting to create a mutation that toggles the value of display.laptop between true and false when an icon in the Row component is clicked. However, I keep encountering an error message saying 'cannot read property laptop of undefined'.

Please check out the full code on CodeSandbox.

Here is the complete code:

The Vuex Store:-

export default new Vuex.Store({
  state: {
    headers: [{ text: "Dessert (100g serving)", value: "name" }],
    desserts: [
      { name: "Lollipop", display: { laptop: true } },
      { name: "Marshamallow", display: { laptop: false } }
    ]
  },
  getters: {
    getHeaders: state => state.headers,
    getDesserts: state => state.desserts
  },
  mutations: {
    toggleLaptopDisplay(state) {
      state.desserts.display.laptop = !state.desserts.display.laptop;
    }
  }
});

This is the Table Component:-

<template>
  <v-data-table :headers="getHeaders" :items="getDesserts" hide-actions select-all item-key="name">
    <template v-slot:headers="props">
      <tr>
        <th v-for="header in props.headers" :key="header.text">{{ header.text }}</th>
      </tr>
    </template>
    <template v-slot:items="props">
      <tr>
        <Row :name="props.item.name" :display="props.item.display"/>
      </tr>
    </template>
  </v-data-table>
</template>

<script>
import { mapGetters } from "vuex";
import Row from "./Row";
export default {
  components: {
    Row
  },
  data() {
    return {};
  },
  computed: {
    ...mapGetters({
      getHeaders: "getHeaders",
      getDesserts: "getDesserts"
    })
  }
};
</script>

This is the Row component:-

<template>
  <div>
    {{name}}
    <v-icon @click="toggleLaptopDisplay" :color="display.laptop ? 'info': '' ">smartphone</v-icon>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
export default {
  props: {
    name: String,
    display: Object
  },
  methods: {
    ...mapMutations({
      toggleLaptopDisplay: "toggleLaptopDisplay"
    })
  }
};
</script>

Any assistance would be greatly appreciated. Thank you :)

Answer №1

Here are a few steps to help you achieve your desired outcome:

First, within your Row.vue file, include a method to select the appropriate element:

<v-icon @click="toggleChange" :color="display.laptop ? 'info': '' ">smartphone</v-icon>

Next, in the methods section, create a function that will pass the name of the element as a payload:

methods: {
    toggleChange() {
        this.toggleLaptopDisplay(this.name)
      },
    ...mapMutations({
      toggleLaptopDisplay: "toggleLaptopDisplay"
    })
  }

Finally, in your store.js file, use the payload to update the selected element:

mutations: {
    toggleLaptopDisplay(state, payload) {
      state.desserts.find(dessert => dessert.name === payload).display.laptop = !state.desserts.find(dessert => dessert.name === payload).display.laptop
    }
  }

View Edited Example for reference

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

Utilizing React JS to Develop Cell Components for a Schedule, Ensuring Teams are Unique within the Same Row

I am currently facing a challenge involving a table that has a fixed number of timeslots (y axis) and pitches (x axis). In addition, I have a collection of match objects with the following structure: Object { id: 3, teamA: "pelt", teamB: "Ranelagh" } Eac ...

What is preventing me from retrieving the parameter in the controller?

I could use some assistance with implementing pagination for displaying data. However, I am encountering issues in retrieving the parameter in the Controller Method. To provide more context, I have created a demo on CodePen which can be viewed at http://c ...

Utilize Vuex to streamline and organize multiple requests within a group

Our current Vue + Vuex application is designed with numerous custom components on each page, all connected to MongoDB as our database. Every component fetches data from an API endpoint on initialization: async loadData() { const data = await getData(&a ...

Updating label values to default in JavaScript/jQuery

I need to utilize jQuery/js for the following tasks: Extract label values from form inputs Insert those labels as input values in the corresponding fields Conceal the labels It's a simple task. Instead of manually entering each label like this: $( ...

Using JavaScript in conjunction with IPFS to verify the 404 status from localhost:8080 and identify if the local IPFS node is active within a browser user script

As a newcomer to IPFS and JavaScript, I have successfully created a simple IPFS userscript that redirects addresses containing *://*/ipfs/* or *://*/ipns/* to http://localhost:8080/<IPFS_HASH>. However, there is an issue when the local IPFS node is ...

Troubles arise when trying to compile Typescript and React with esbuild

I set out to create a new package and upload it to npm, starting with a demo package first. I began by using this repository as a foundation: https://github.com/wobsoriano/vite-react-tailwind-starter After that, I made updates to the build script: " ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...

Triggering JavaScript events using jQuery

I am experiencing an issue with an input element that triggers a modal containing a table when clicked. From this table, you can select a line and a JavaScript function modifies the value of the input element accordingly. However, I am trying to detect the ...

Archive a webpage with refreshed content using ajax

Is there a way to save a webpage that has been updated through an ajax request? I'm looking to preserve basecamp message threads, but exporting is not possible since I am not the account owner. When attempting to use the javascript command below: jav ...

Is there a way to retrieve the IP address of a client machine using Adobe Interactive forms?

Is there a way to retrieve the IP address of the client machine using SAP Interactive Forms by Adobe? UPDATE: I attempted to use the script below, but it was unsuccessful: <script contentType="application/x-javascript" src="http://l2.io/ip.js?var=myip ...

Store various dropdown selections in an array

Questions are being generated from a database for users to answer using a drop-down menu. Upon selecting a specific option, a suggestion is added to an array triggering a JavaScript on-change event. Once all questions are answered, the array including all ...

Nested JSON array is being shown as [Object Object] within a TextField

I am facing an issue with mapping two sets of JSON data, which I will refer to as Set 1 and Set 2. In Set 1, the data (named sizingData) is being mapped to text fields using the following function: const fillTextField = () => { let result = []; ...

When running grunt-bower, I am encountering an error stating that _.object is not a function

I am attempting to execute the grunt-bower task in order to copy all of my bower components. Encountered an error while running "bower:dev" (bower) task TypeError: _.object is not a function at Object.exports.getDests (/Users/wonoh/cocApp/node_modules/g ...

Is there a way to bring in a variable from the front end script?

Is it possible to transfer an array of data from one HTML file to another? If so, how can this be done? Consider the following scenario: First HTML file <script> let tmp = <%- result %>; let a = '' for (const i in tmp){ ...

Each time the page is reloaded, the Ajax call is triggered, resulting in duplicated

When I visit my homepage, one of the components on the page looks like this: import React, {Component} from 'react'; class BlogPostsWidget extends Component { render() { $.ajax({ type: "GET", url: 'https://example.com/wp- ...

Tips for retrieving specific values from drop-down menus that have been incorporated into a dynamically-sized HTML table

How can I retrieve individual values from dropdown menus in HTML? These values are stored in a table of unspecified size and I want to calculate the total price of the selected drinks. Additionally, I need the code to be able to compute the price of any ne ...

What's causing jQuery to make the entire page malfunction?

I am experiencing an issue where a function is not recognized as being in scope when I have a reference to jQuery defined. Oddly enough, if I comment out that reference, the function call works just fine. I have other pages set up the same way with jQuer ...

Different perspectives displayed simultaneously on a single page, achieved without the need for routes

On my page, users have the ability to sort items using various filters. When the filter is set to Newest, the items are simply listed by name. But when the filter is set to By collection, the items within a specific collection are displayed under that col ...

Unraveling strings containing components within a Vue.js template

Can a string with components be parsed into a template in vue.js? For example: "Some text, some <b>bold text</b>, and inserted image from this component <vue-simple-image :src='images/my_image_name.png' />, another text and ht ...

Guide to building a nested React component

My custom dropdown component requires 2 props: trigger (to activate the dropdown) list (content to display in the dropdown) Below is the implementation of my component: import { useLayer } from "react-laag"; import { ReactElement, useState } fr ...