What is the best way to include arrays in VueJS?

Currently, I am working with two arrays in my Vue application. The first array called desserts lists all the desserts that I have. The second array, moreDesserts, displays checkboxes with values. When a user selects a checkbox, the value is added to the selectedDessert array in Vuex state. My goal is to create a method where upon selecting a checkbox and clicking the button ADD ARRAYS, the selected array should be concatenated with the desserts array. I have set up a mutation called addArrays for this purpose, but it doesn't seem to be functioning as expected.

If you want to see the code in action, please visit this CodeSandbox.

This code snippet shows my HelloWorld Component:


    <template>
  <div class="ml-3">
    <v-flex v-for="el in getDesserts" :key="el.name">
      <div class="title mt-2">{{el.name}}</div>
    </v-flex>
    <v-flex v-for="dessert in getMoreDesserts" :key="dessert.fat">
      <v-checkbox v-model="selectedDessert" :label="dessert.name" :value="dessert"></v-checkbox>
    </v-flex>
    <v-btn @click="addArrays">Add Arrays</v-btn>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "HelloWorld",
  data() {
    return {};
  },
  computed: {
    ...mapGetters({
      getDesserts: "getDesserts",
      getMoreDesserts: "getMoreDesserts",
      getSelectedDessert: "getSelectedDessert"
    }),
    selectedDessert: {
      get() {
        return this.getSelectedDessert;
      },
      set(val) {
        return this.$store.commit("setSelectedDessert", val);
      }
    }
  },
  methods: {
    addArrays() {
      this.$store.commit("addArrays");
      console.log(this.selectedDessert);
    }
  }
};
</script>

Here is my Vuex Store setup:


import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    desserts: [
      { name: "Yogurt", calories: 169, fat: 22.0 },
      { name: "Chocolate", calories: 270, fat: 19.2 }
    ],
    moreDesserts: [
      { name: "Ice Cream", calories: 280, fat: 14.0 },
      { name: "Cake", calories: 400, fat: 35.0 }
    ],
    selectedDessert: []
  },
  getters: {
    getMoreDesserts: state => state.moreDesserts,
    getSelectedDessert: state => state.selectedDessert
  },
  mutations: {
    setSelectedDessert(state, payload) {
      state.selectedDessert = payload;
    },
   addArrays(state) {
     state.desserts.concat(state.selectedDessert);
     state.selectedDessert = [];
    },
  },
  actions: {}
});

Your assistance on resolving this issue would be greatly appreciated. Thank you.

Answer №1

So close! When you use the concat method, a new array is returned instead of modifying the original desserts array. Make sure to update your code like this:

state.desserts = state.desserts.concat(state.selectedDessert);
, and you'll be good to go!

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

Vue: Choosing an option during the execution of setInterval

I'm facing an issue where I can't select an option while a setInterval function is running on the page. The main problem is that an option cannot be selected at the same time as the setInterval timer fires. let updateDelay = 100; var vueObj = ...

The resolve in Angular UI-Router is not being properly injected into the controller

As a Java developer venturing into the world of Angular and Express, I am encountering challenges along the way. To gain hands-on experience, I am attempting to create a small application using these technologies. The Goal: I have provided a password rese ...

What is the best method for me to filter the values in my array?

I need to add a value to an array based on certain conditions. My code looks something like this: var newEmployee = []; $scope.employees = [{'id':1, 'new':true},{'id':2, 'new':false}{'id':3, 'new&apo ...

Using JavaScript to convert the text within a div into negative HTML code

I am working with this specific div: <div class="signs" id="signs" onclick="toggle()">&#43;</div> It currently displays the positive sign. I have set up a JavaScript function that is triggered when the div is ...

Displaying an image in AngularJS using a byte array received in the response

Dealing with a service that adds properties to a file and returns it as a byte array in the response. I'm struggling to display it properly since it's in byte form. Attempted converting it to base64 but still showing raw bytes. PNG IHDR&L ...

What is the reason for the alterations made to a basic object causing an impact on a responsive object even when they are distinct entities

Below is the code snippet I am working with: const cellsArray = Array.from(Array(fieldSize.height), (_, y) => Array.from(Array(fieldSize.width), (_, x) => new Cell(y, x)) ); const fieldCells = ref(cellsArray); console.log(fieldCells.value[0][0] = ...

What is preventing us from assigning the jquery selector object to a different object's property for later use?

I'm facing an issue in the code below where I am trying to assign a jQuery selector object to another object property but it's not functioning as expected. Can you help me identify what mistake I might be making? index.html <html lang="en"&g ...

The Next.js build process encountered an error when building due to an issue with plotly.js (The build failed with a ReferenceError: self is

Whenever I attempt to build the Next.js app for production using the yarn build command, I encounter the following error. Strangely enough, everything works perfectly fine on the development server when using the yarn dev command. The app employs the react ...

What is the best way to set up a Vue bus to handle global events?

I am working on a Vue project within a Node/Webpack/Vue Router environment and attempting to set up a global event handler or bus. However, I am running into an issue where it is showing as undefined. Below is how I have set it up: main.js: //Defining th ...

AssistanceBubble.js with ASP.NET UpdatePanel

Looking for guidance on implementing HelpBalloon.js () within an ASP.NET UpdatePanel. Experiencing issues with image loss after a postback. ...

Pressing the button on the form has no effect

I am testing a login screen using NodeJS, but I am facing an issue where the submit button does not redirect to the dashboard screen as intended. What could be missing in the code? The submit button should direct to the dashboard screen that I have created ...

Preventing all hammer.js (angular-hammer) interactions except for single taps

Utilizing the angular-hammer module in my app, I am keen on refining its performance specifically for the tap event. Given that no other gestures are required, I aim to enhance efficiency by excluding unnecessary listening functions, such as double tap. As ...

Why does Vue prompt me with 'mutate Vuex store state outside mutation handlers' when I try to commit?

<template> <div class="counter-warp"> <p>generate</p> <div class="statusCon"> <p class="card"> last: {{completed.length > 0 ? completed[completed.length - 1].text : ''}} </p& ...

Looking to determine if a specific element is assigned multiple class names

Help needed! Can you tell me how to check if an element contains more than one classname using pure javascript, without using jQuery? For example: If #test has both the classnames "classA and classB", then { alert(true) } else { alert(false) } Here is ...

Obtain the value of v-model in a child component within VueJS

In my Vuetify App, I have implemented a Vue2Editor using a custom component called text-editor. Here is how it looks: <vue-editor :value="text" @input="updateText" ></vue-editor> The props for this component are defined as follows: props ...

Retrieve client-side environment variables

When making multiple API calls within my components using the fetch method, I found myself constantly having to determine which environment I was in. To streamline this logic, I created a Utils class that provides the appropriate base URL: export default c ...

The disappearance of a Python numpy mask when assigning an array to another array

Currently, I am working with geodetical data and using masks to cover areas without data. One issue I encountered involves designing an array with different time series data for various locations on the earth. The problem arises when I assign separate spot ...

`Next application will have all accordions simultaneously opening`

Is there a way to make the accordion open only one item at a time? Currently, when I click on one accordion item, all of them expand simultaneously. The data is being fetched from a local JavaScript file and consists of a list of objects with questions a ...

How to deactivate the <a> tag with Ant Design UI Library

Is there a method in the antd UI library to disable a link? The disabled attribute is not supported by the a tag according to MDN. This code snippet works in React but the link remains clickable when using Next.js. <Tooltip title={tooltip}> <a ...

In ES6, instantiate a fresh new instance of this

Can a new instance of self/this be generated using ES6 inside a static method? For instance; class myClass { static model() { return new this; } } Is there a standard approach for this situation? Thank you very much. ...