What is the best way to utilize v-model with an array of strings in a Vuex store when using v-for

Encountered an issue while trying to set a value in an Array within the Vuex Store:

VueCompilerError: v-model cannot be used on v-for or v-slot scope variables because they are not writable.

Seeking alternatives to achieve this without creating a local copy of the Vuex model array in the component.

The template for my component.vue:

<q-input v-for="phone, index  in CompanyPhones" :key="index" v-model="phone" mask="(##) ### ## ##" stack-label label="Phone" />

The script for my component.vue:

setup () {
    const $store = useStore()
 const CompanyPhones = computed({
      get: () => $store.getters['CompanySettingsModule/getCompanyPhones'],
      set: (val) => {
        $store.commit('CompanySettingsModule/setCompanyPhones', val)
      }
    })
 return {  CompanyPhones, }
}

Vuex module state.ts:

function state (): CompanySettingsInterface {
  return {
    CompanyPhones: ['', '', ''],
  }
}

Mutation function in Vuex module mutations.ts:

setCompanyMails (state: CompanySettingsInterface, val)  { state.CompanyMails = val },

Getter function in Vuex module getters.ts:

getCompanyPhones (state: CompanySettingsInterface)  { return state.CompanyPhones  },

Answer №1

Your custom getter/setter function is limited to handling arrays only, which poses a challenge when updating nested values like companyPhones[index]. This limitation mirrors Vue's reactivity behavior, requiring you to replace the entire array with a clone whenever a child value is updated directly. One way to work around this is by creating a method:

//script
methods: {
  updateCompanyPhone(value, index) {
    const { companyPhones } = this; // ES6 destructuring syntax
    companyPhones[index] = value;
    this.companyPhones = companyPhones;
  }
}

//template
<q-input v-for="phone, index in CompanyPhones" :key="index" :model-value="phone" @update:model-value="value => updateCompanyPhone(value, index)" mask="(##) ### ## ##" stack-label label="Phone" />

By breaking down v-model into its constituent parts - :model-value and @update:model-value (Vue3), you gain more control over its functionalities.

If this scenario repeats frequently, consider developing a Higher Order Component that manages an Array containing nested values through a value prop and update:value emit (for use with v-model). Include a slot for custom form(field) input to update nested values, along with functions like splice/push for adding/removing items from the array.

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

Converting JSON Arrays into Typescript Arrays

I am working with a JSON file that contains an array object like this: [ { "VergiNo": "XXXXXXX" }, { "VergiNo": "YYYYYY" }, { "VergiNo": "ZZZZZZ" } ] After importing this JSON file into my Typescript file, import * as companies f ...

Getting an array of objects that have been sent via Ajax in Laravel can be achieved by accessing the

Currently, my setup involves using Laravel alongside Vuejs and AXIOS for handling HTTP requests. I'm faced with a challenge when sending a post request containing an array of objects. The question now is, how can I extract and work with this data in m ...

How to compare and filter items from two arrays using TypeScript

I am looking to filter out certain elements from an array in TypeScript Original Array: [ {"Id":"3","DisplayName":"Fax"}, {"Id":"1","DisplayName":"Home"}, {"Id":&quo ...

Influence of scoped styles on external webpages

I'm facing an issue with my nuxt app where I have two pages, each with different background styles. However, the background of one page is overriding the other. index.vue <style scoped> body { background-color: #ffffff; } #banner { backgr ...

"Encountering Devextreme Reactive Errors while navigating on the main client

Attempting to integrate Devextreme with Material Ui in my Typescript React app has been a challenge. Despite following the steps outlined in this documentation and installing all necessary packages, I am encountering issues. I have also installed Material ...

Access Vuex Getters in a separate JavaScript file

Within the file /store/user/getters.js: function getLoggedIn (state) { return state.loggedIn } In a different file, router-auth.js, I attempted to access the value (true or false) of getters.getLoggedIn in the following manner: import user from '.. ...

Leveraging the power of Angular 5 to seamlessly integrate two distinct components on

I am exploring a way to render an additional component on the current page instead of navigating to a new one. Here is my setup: <button mat-button color="primary" [routerLink]="['/tripspath', trip.tripId]" style="cursor: pointer">View Rou ...

Utilizing Vue.js 2.x to send a REST API request with a collection of objects

I currently have an array of objects stored in state, and my goal is to send this entire structure to a back end API for processing and receive a new set of values in return. Below is a simplified representation of this structure as viewed in the develope ...

What could be the reason for the malfunctioning transition effect in my slider animation?

Having trouble getting my slider animation to work. I've tried different CSS styles but the slide transition is not functioning as expected. When one of the buttons is clicked, I want the slide to change from right to left or left to right. Can anyone ...

Cease the repetitive running of the function in a gentle manner

When working with typescript/nodejs, how can one gracefully shutdown a component that is continuously performing tasks? For instance, I would like to allow the user to send a SIGINT signal, such as by pressing <ctrl+c>, in order to halt the program g ...

Having trouble retrieving the parent object in Angular OnInit method?

I am facing an issue with attaching a custom validator to an Angular Form Control. The Form Controls are initialized in the ngOnInit method, and I want the validator to check if a field has input only when a boolean class member this.shouldCheck is true. ...

Instructions on resolving the issue: The type 'string | ChatCompletionContentPart[] | null' cannot be assigned to type 'ReactNode'

I've been working on my first Saas App, similar to a ChatGPT, using NextJs with the OpenAI Api. Most of the development was based on a YouTube tutorial until I encountered two errors caused by an update in the OpenAI version. Despite trying various so ...

Click function for mat-step event handler

Is it feasible to create a click event for the mat-step button? I want to be able to add a (click) event for each mat-step button that triggers a method. Essentially, I am looking to make the mat-step button function like a regular button. You can find mo ...

Running complex Firestore query within Cloud Functions

Currently, I am developing triggers that interact with a Firestore movie and user database. The main goal of one trigger is to present a new user with a list of top-rated movies in genres they have selected as their favorites. To achieve this, I store the ...

"Exploring the power of Vue-router with complex, multil

After reviewing the given Layout component: This is how the Layout looks like: <template> <div class="container"> <div class="sidebar-container"> <router-view name='sidebar'></router-view> </ ...

Using Laravel in combination with Vue Js along with Vuetify and Vuelidate

Can someone shed some light on the validation process in Laravel and Vue JS? I find myself using Vue JS independently of Laravel, which has led me to question whether it's best to handle validation on the backend, frontend, or both. When working wit ...

Tips for updating the icon based on the active or inactive status in ag-grid within an angular application

HTML* <ng-template #actionButtons let-data="data"> <div class="cell-actions"> <a href="javascript:;" (click)="assign()"> <i nz-icon nzType="user-add" nzTheme= ...

What steps should be taken to enable SCSS in Jest for unit testing in TypeScript Next.js?

I am facing an issue with the scss import in my project. I have attempted to solve it by using mockup and identity-obj-proxy, but neither of them seems to work. I suspect that there might be a problem with my regex expression. The specific error arises fr ...

Computed property not properly updating the v-if condition

RESOLVED: I have found a solution that almost solves the issue. By removing <div v-if="isFrameLoaded"> and binding the source data to <video>, the video now loads simultaneously with the request being sent. There is no data in getBLOB ...

Vue2's v-for does not update nested component props when the parent element is removed

In my application, I have implemented two Vue components. One component displays a list of "days" and the other component displays the list of "locations" for each "day". For example, "Day 1" may include locations such as "Berlin", "London", and "New York" ...