Tips on detecting array changes in a computed property originating from Vuex

I am currently working with an array of computed properties that are generated from the store's state:

computed: {
  ...mapGetters([
    '$tg',
  ]),
  ...mapState({
    podcastList: state => state.listening.podcastList,
  }),
  tabList: {
    get() {
      const questionTitle = this.$tg('questions');
      const list = this.podcastList.map((podcast, index) => ({
        ...podcast,
        title: `${questionTitle}${index + 1}`,
        answers: [...podcast.answers],
      }));
      return list;
    },
    set(value) {
      // I want to dispatch an action here...
      console.log('set', value);
    },
  },
}

The podcastList is constructed as an object array:

[ 
  { 
    id: 1,  
    answers: [ 
      { id: 1, content:'foo'}, { id: 2, content: 'bar'}
    ]
  }, //.....
]

To display a group of input elements bound to the answers, I use the v-for directive. It appears as follows:

<div class="columns is-vcentered" v-for="(answer, index) in tab.answers" :key="index">
 <input type="text" v-model="answer.content"/>
</div>
// Here, tab represents an element within my tabList

The issue arises when I try changing the input values - the computed setter does not trigger and I receive the following message:

"Error: [vuex] do not mutate vuex store state outside mutation handlers."

While I understand that direct state modifications are not allowed, I am unsure how to dispatch an action similar to the example shown on the official website. Any assistance would be greatly appreciated. Thank you.

Answer №1

v-model needs to be connected with tabList like v-model="tabList" in a component for it to work properly.

To modify each answer individually, you should use value and @input instead of v-model:

<div class="columns is-vcentered" v-for="(answer, index) in tab.answers" :key="index">
 <input type="text" :value="answer.content"
       @input="$store.commit('updateAnswer', { podcastId: tab.id, answerId: answer.id, newContent: $event.target.value })" />
</div>
// tab represents an item from my tabList

For the mutation updateAnswer, you can define it as follows:

mutations: {
  updateAnswer (state, { podcastId, answerId, newContent }) {
    state.listening.podcastList
        .find(podcast => podcast.id === podcastId)
        .map(podcast => podcast.answers)
        .find(answer => answer.id === answerId).content = newContent;
  }
}

--

You can streamline the process by creating a method:

methods: {
  updateAnswer(tab, answer, event) {
    this.$store.commit('updateAnswer', { podcastId: tab.id, answerId: answer.id, newContent: event.target.value });
  }
}

Usage example:

<input type="text" :value="answer.content" @input="updateAnswer(tab, answer, $event)" />


Alternatively, you can create a functional component:

Vue.component('answer', {
  template: `
    <input type="text" :value="answer.content"
           @input="$store.commit('updateAnswer', { podcastId: tab.id, answerId: answer.id, newContent: $event.target.value })" />
  `
  props: ['tab', 'answer']
})

Usage example:

<div class="columns is-vcentered" v-for="(answer, index) in tab.answers" :key="index">
 <answer :tab="tab" :answer="answer"/>
</div>

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

I'm encountering an issue with Regex.test

When working with the following JavaScript code... $.post(url, data, function (json) { var patt = new RegExp('/^\[{"dID":/'); if (patt.test(json)) { //output json results formatted } else { //error so o ...

Safari's Failure to Execute Ajax Requests

My HTML page includes an ajax request that is functioning properly on Firefox, but does not work on Safari. While debugging, I noticed that the readystate is undefined and the status is "". Can anyone suggest why it might not be working on Safari? Javascr ...

Initiate data extraction immediately upon the DOM being fully loaded using NightmareJS

Currently, I am utilizing nightmarejs and facing a challenge that I am struggling to resolve. After using the goto(URL) command, I then proceed to use the evaluate() command to execute specific operations on the webpage. However, I have noticed that while ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

PHP is not receiving any data from the Ajax request

I'm currently attempting to set up my first Ajax example on my MAMP server. Here's how my ajax.html file looks: <html> <head> <script src='ajax.js'></script> </head> <body onload = 'ajax()'> ...

"Exploring the power of NodeJS with createServer, dealing with

Can instances of global.request potentially collide in this NodeJS scenario? I have a basic web server set up in NodeJS where I am globally exposing the request that is created: http.createServer(function(req, res) { global.request = req; // do ...

Express fails to handle the POST request

Using ejs, express, nodeJS and mySQL has been great so far. However, I'm facing an error with this code: Cannot POST /search. I believe the index.ejs and app.js files are okay, but I suspect there's a problem with the searchRouter... app.js cons ...

Use v-bind to redirect to Localhost rather than the original link

The current button is linked to the data from v-for="book in books". The URL in the database is www.google.com. <md-button v-bind:href="book.url" target="_blank">SEE ORIGINAL</md-button> However, when loading the page on localhost, the butt ...

Receiving communication without the need for port forwarding

My goal is to establish a system where a server can send messages to clients at any given time, ensuring that when a message is sent, it is received almost immediately (ideally within 1 second or less). I am looking for a way to achieve this without having ...

Using jQuery to handle events across multiple elements

Could I achieve something similar to this? I currently have several variables assigned to DOM elements. Rather than querying the DOM again to set event handlers, I would like to utilize the variables I already have. var a = $("#foo"); var b = $("#bar"); ...

What is the best way to eliminate a JSON header?

Here is the JSON data I have: { "folder": [ { "$": { "id": "471841542", "name": "Manajemen Pemasaran", "description": "", "user_id": "186868958", "shared": "1", "shared_l ...

"Responding to an Ajax request with a .NET Core server by sending an xlsx

My web application exclusively supports .xlsx files. I have implemented a function in my controller that converts .xls files to .xlsx format successfully. When trying to open a .xls file, I send it via an Ajax request. However, the converted .xlsx file do ...

Google-play-scraper encounters an unhandled promise rejection

I'm trying to use the google-play-scraper library with Node.js, but I keep encountering an error when passing a variable as the 'appId'. How can I resolve this issue? Example that works: var gplay = require('google-play-scraper') ...

Is the functionality compatible with all browsers even though <div /> is not recognized as a proper HTML element?

Can the code $("<div />").appendTo($mySelector) be relied upon for safety and cross-browser compatibility, considering that <div /> is not a valid HTML element? I pose this question because it seems much simpler to use than $("<div><d ...

The onchange event in the dropdown activates a function, however, there is no alteration observed in the three

I am attempting to create a dynamic display of a green or brown floor on a webpage using three.js, based on the selection from a dropdown list. However, I am encountering an issue where the floor images do not update even though the function is being execu ...

Ways to retrieve the specified data in Javascript in string format

I'm facing an issue where the data I passed from a JavaScript array to a Java servlet and back to JavaScript is showing as "undefined." Check out my JavaScript code below: var buildingNumbers = []; // Let's assume the values of buildingNumbers ...

The outcome of the AJAX RSS Reader remains unpredictable

Utilizing the AJAX RSS Reader (visit this link) for extracting RSS data from my URL: http://vtv.vn/trong-nuoc.rss In my php file (readRSS.php): <?php $url = ("http://vtv.vn/trong-nuoc.rss"); $xmlDoc = new DOMDocument(); $xmlDoc->load($url); $ ...

How can I incorporate images into my Vue Select dropdown?

Currently, I am using the vue-select component to display dropdowns on my website. These dropdowns are populated with data provided through the :options attribute. Specifically, I am working on implementing a credit card dropdown and would like to includ ...

What causes the discrepancy in the output values of the sha1 algorithm when using the packages object-hash and crypto/hashlib

On my frontend, I have implemented a JavaScript function that compares two sha1 hashes generated by the object-hash library. This is used to determine if there are any changes in the input data, triggering a rerun of a processing pipeline. To interact wit ...

Error during CSS minification while running npm build in [vue.js] application

Every time I attempt to run 'npm run build', I encounter this error and realize that there are no CSS files present. ERROR Error: CSS minification error: Unexpected colon found.. File: css/app.86f0ef2e.css Error: CSS minification error: Unexpec ...