Modifying the title of a dynamically generated element with a Vuex mutation

I'm facing a confusing issue where I am unable to manipulate the title of a dynamically added element independently. The title seems to change for all elements created in the process.

What I am aiming for is to be able to call multiple components and manipulate the title of a specific one without affecting others.

In my scenario, Vuex correctly receives the indexes of detail goals, so it's puzzling why the DG_TITLE_MUTATION mutation is causing all detail goal names to change. Even when I retrieve an object from the server with two detail goals and modify their names as desired, the problem persists with new elements created during the session.

I am stuck here and would really appreciate some help.

The first component with a v-for directive below adds and displays the problematic components:

<template>


    <q-btn icon="add" label="add detail goal" @click="addDetailGoal"/>

    <q-list v-for="(detailGoal, index) in $store.state.documents[0].document.content.mainGoal.detailGoals" :key="index" :name="index">
      <goals-details :thisIndex="index"/>  
    </q-list>    
 
</template>
<script lang="ts">
//jj. Main import
import { defineComponent} from 'vue';
//jj. Components
import GoalsDetails from './GoalsDetails.vue';
//jj. Store
import { useStore } from 'src/store';
//jj. types
import { detailGoal } from './models'

export default defineComponent({
    name: 'NewDocument',
    components:{
      GoalsDetails
    },
    props:{
      grantObj:{
        type: Object
      },
    },

    setup() {
    
    //jj. main settings
    const store = useStore()

    //jj.  This is part pushed to main object when user use add main goal btn
    const detailGoal:detailGoal= {
      id:'',
      title:'New detail goal',
      description:'',
      quote:'',
      tasks:[],
    };       

    //jj. Add addDetailGoal
    function addDetailGoal(){ 
      store.commit('ADD_DETAIL_GOAL', detailGoal) 
    }

    return { 
      //jj. functions
      addDetailGoal,
    };
  },
})
</script>

Below is the component with the title to be manipulated, with an input connected to a mutation function:

<template>
<q-btn icon="delete" label="delete" @click="removeDetailGoal" class="bg-purple text-white"/>
    <q-input v-model="detailGoalTitle" label="Project title" class="q-ml-sm"/>
<script lang="ts">
//jj. vue
import { defineComponent, ref, computed} from 'vue';
//jj. components
import ProjectTasks from 'components/ProjectTasks.vue'
//jj. types
import { task } from './models'
//jj. Store
import { useStore } from 'src/store';

export default defineComponent({
  
  name: 'GoalsDetails',
  props:{
    thisIndex:{
      type: Number
    },
  },
  components:{
    ProjectTasks,
  },
  setup(thisIndex) {
    const store = useStore()

    // *******************************************************************************************
    // jj. DETAIL GOAL SECTION
    // *******************************************************************************************
    //jj. Edit detail goal title 
    let detailGoalTitle = computed({
      get: () => {
        if(store.state.documents && typeof thisIndex.thisIndex == 'number'){
          return store.state.documents[0].document.content.mainGoal.detailGoals[thisIndex.thisIndex].title}else{
        return 'no document'
      }},
      set:( val ) => store.commit('DG_TITLE_MUTATION', {val, thisIndex})
    })


    function removeDetailGoal(){
      store.commit('REMOVE_DETAIL_GOAL', thisIndex.thisIndex)
    }
    // *******************************************************************************************
    // jj. TASKS SECTION
    // *******************************************************************************************
    //jj.  This is part pushed to main object when user use add main goal btn
    const taskTemplate:task= {
          id:'', 
          title:'New Task',
          results:[]
    };
    
    //jj. Add Task
      function addTask(){
      console.log(thisIndex.thisIndex);// this is proper index
      store.commit( 'ADD_TASK', {taskTemplate, thisIndex} )
    }


    return { 
      //jj. detail goal section
      detailGoalTitle, 
      removeDetailGoal,
    };
  },
})
</script>

The Vuex mutations:

//jj. Add next detailGoal
      ADD_DETAIL_GOAL(store, detailGoal: detailGoal){
        if(store.documents){store.documents[0].document.content.mainGoal.detailGoals.push(detailGoal)}
      },

      //jj. Edit detail goal title
      DG_TITLE_MUTATION( store, {val, thisIndex}:{val:string, thisIndex:{thisIndex:number}}){
        if(store.documents){store.documents[0].document.content.mainGoal.detailGoals[thisIndex.thisIndex].title = val 
        }
      },

Answer №1

Special thanks to James from a different online community for providing me with the solution. I realized that my error stemmed from incorrectly using JavaScript. Instead of passing a new object, I was passing a reference to an existing one called detailGoal. Here is the snippet of code where the mistake occurred:

 function addDetailGoal(){ 
 store.commit('ADD_DETAIL_GOAL', detailGoal) 
}

In order to pass a new object, I needed to create a function for that purpose:

function detailGoal():detailGoal{ 
 {
   id:'',
   title:'New detail goal',
   description:'',
   quote:'',
   tasks:[],
  };       
};

function addDetailGoal(){ 
 store.commit('ADD_DETAIL_GOAL', detailGoal()) 
}

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

Uncovering the mystery of retrieving form values from dynamic HTML in Angular 2

As a beginner in Angular 2, I am facing challenges extracting values from Dynamic HTML. My task involves having some Form Inputs and injecting Dynamic HTML within them that contain additional inputs. I followed the example by @Rene Hamburger to create the ...

The binding element 'dispatch' is assumed to have the 'any' type by default. Variable dispatch is now of type any

I came across this guide on implementing redux, but I decided to use TypeScript for my project. Check out the example here I encountered an issue in the AddTodo.tsx file. import * as React from 'react' import { connect } from 'react-redux ...

VS Code failing to refresh TypeScript in Vue files

Currently, I'm using Vue with Vue Single File Components (SFC) and TypeScript in vscode. However, I've noticed that the types I create in a .d.ts file are not being applied or updated in my .vue files. It's only when I reload the window that ...

Strange black backdrop in dialog component

Today I came across a rather peculiar issue and was wondering if anyone else had experienced it and found a solution. The problem is pretty straightforward - when I load up my Vue component with a dialog element from the Element-UI library, the background ...

The issue of calling the store() function on null in Laravel with Nuxt

I'm encountering an issue with saving data in Laravel from my Nuxt Application. I successfully created data using Postman, but for some reason it's not working here. Controller $book = Book::create([ 'name' => $request ...

Merge generic nested objects A and B deeply, ensuring that in case of duplicate properties, A's will take precedence over B's

Two mysterious (generic) nested objects with a similar structure are in play: const A = { one: { two: { three: { func1: () => null, }, }, }, } const B = { one: { two: { three: { func2: () => null, ...

The sign out option fails to erase the data stored in Local Storage

After implementing a login feature that stores a token in local storage, I encountered an issue with the logout button. The intention was for the button to delete the token from local storage and set the user to null upon clicking it. However, this functio ...

Dynamic Fill Colors in SVG File Through Vue Components

I am currently developing a unique social media platform using VueJS 3. For the design aspect, I incorporated Twitter's iconic logo saved as an .svg file, easily displayed using the <img /> tag. To modify its color, I utilized the fill="#f ...

Is it possible to utilize the pre-installed "Component" component within a render function?

Can the <component> element be utilized in a render function? I encountered an error message while attempting to do so: Unknown custom element: <component> - have you properly registered the component? For recursive components, ensure that th ...

Trigger a Vuex action from a component once a mutation has finished

I am facing a situation with my Vue component where I need to call a Vuex action in the create hook. This action, an api.get request, fetches data and then dispatches a mutation. Once this mutation is completed, I have to trigger an action in another store ...

How to bring in a specific module using its name in TypeScript

Can a module in typescript import itself by its own name? For example, let's consider a module called my-module with various tests. Is it possible to import it within the tests using import ... from "my-module" instead of using a local path like impo ...

Is ts-node necessary for using TypeScript in Node.js?

Having trouble setting up a Node.js application in Visual Studio Code using TypeScript due to issues with importing modules. Initially, I created an index.ts file with the import statement -> import config from './app/config.json'; This resu ...

After exiting the Vue PWA, a blank screen appears

After successfully creating a PWA Application, everything seems to be working fine. However, there is a problem: Users install the PWA on their desktop and it functions properly. But when they close and reopen it, only a blank page appears. The same i ...

Building Unique Password Validation with Angular 5

I'm attempting to implement custom password validation for a password field. The password must be a minimum of 8 characters and satisfy at least two of the following criteria but not necessarily all four: Contains numbers Contains lowercase letters ...

Error message: Insufficient credentials to access DRF system

For some reason, my app is no longer allowing users to log in after making changes to their profile. I have a nested User serializer with the profile serializer fields (one-to-one relationship) using Djoser for the urls. When attempting to update the user ...

The browser is not displaying the HTML correctly for the Polymer Paper-Menu component

I attempted to implement a paper-menu, but I am facing issues with the rendered HTML and its interaction. When I click on a menu item, the entire list disappears due to the paper-item elements not being properly placed inside a key div within the paper-men ...

Keep the code running in JavaScript even in the presence of TypeScript errors

While working with create-react-app and typescript, I prefer for javascript execution not to be stopped if a typescript error is detected. Instead, I would like to receive a warning in the console without interrupting the UI. Is it feasible to adjust the ...

Setting the "status" of a queue: A step-by-step guide

I created a function to add a job to the queue with the following code: async addJob(someParameters: SomeParameters): Promise<void> { await this.saveToDb(someParameters); try { await this.jobQueue.add('job', ...

CSS radio button not showing up on Safari browser

I am encountering an issue with my vue app where it functions correctly on Google Chrome but experiences problems on Safari. Specifically, the issue arises with components containing radio buttons. Upon clicking on a radio option, the selected color (blue) ...

Transform 'ast' back into a template string within Vue

I am currently using vue-template-compiler to modify attributes within a specific div. Once I have made the necessary changes, I need to convert the ast's back to template string format. How can this be accomplished? Is there a tool similar to dom-se ...