Managing multiple properties linked to a main component array in VueJS

I am facing a challenge with a list of components that I would like to make editable and replicate the state to the parent component.

The list component is defined as:

Vue.component("shortcuts", {
  props: {
    shortcuts: Array
  },
  template: '...<shortcut-entry v-for="(shortcut, index) in shortcuts" :key="index" :shortcut="shortcut" @remove="remove(index)"></shortcut-entry>...'
})

It is used with a model like this:

<shortcuts :shortcuts.sync="shortcuts"></shortcuts>

Now each shortcut-entry component will contain multiple values that I want to pass back to the main list of objects:

    Vue.component("shortcut-entry", {
      props: {
        mod_ctrl: Boolean,
        mod_alt: Boolean,
        mod_shift: Boolean,
        keypress: String,
        action: String,
        ...
      },

Each of these properties has its own checkbox or input field on the page, for example: <input ... v-model="action">. While I can manually handle updating the parent component for each change, it seems like a lot of repetitive code.

Is there a way to automatically propagate any changes made to these props back to the parent component? (while avoiding the "Avoid mutating a prop directly" warning)

So far, moving all props into another level and binding them with .sync seems to work, but I am exploring a more explicit solution that declares these options upfront.

Answer №1

If you want to utilize the sync modifier alongside props object notation, consider using v-bind.sync="shortcut" instead of v-bind="shortcut".

This approach allows the shortcut component to define all props (rather than just the options object) while still being able to notify the parent about changes.

To implement this, adjust how you bind your inputs. Instead of

<input ... v-model="action">
, use
<input ... v-bind:value="action" v-on:input="$emit('update:action', $event.target.value)">
. However, different <input> types may have varying names for the value and change event, as outlined in Vue documentation.

If you prefer to continue using v-model, you can create a computed property for each prop and utilize

v-model="actionComputed"
:

computed: {
  actionComputed: {
    get: function() { return this.action },
    set: function(value) { this.$emit('update:action', value) }
  }
}

However, this method results in additional boilerplate code.

In summary, if you wish to predefine all props (instead of a single prop of type object), some level of boilerplate is unavoidable. While it is possible to reduce this by dynamically generating computed props for v-model similar to how Vuex helpers work, the effort may not be worth it. It might be simpler to pass an object and allow the <input> components to handle property mutations...

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

Creating pagination in Vue using an array of objects

I'm new to Vue and arrays and I need help paginating my json array so that only 10 items are displayed per page. Currently, all the items in the array are being shown in the <tr> body. I've tried different methods without success. Can someo ...

Guide to extracting a key from the route module with the help of vuex-router-sync

I have a Vuex store setup as shown below, and I am using vuex-router-sync to keep it in sync. This plugin adds a router module to my store. However, I am unsure of how to retrieve this object from the store since there are no associated getters with this m ...

Use the ng-repeat directive to display multiple items and let the user input a quantity for each item. Then, in AngularJs, gather all the form data, including the repeated items and their quantities, and

Hey there! I have a question related to AngularJs: How can I repeat pre-selected items using (ng-repeat) and allow users to enter a quantity for each item in a subsequent step, then submit all the form data? I'm wondering if adding $index to the repe ...

jQuery: Locate and eliminate any images in the text that appear after a specific group of tags if no images are present

Currently, I am in the process of developing a feed reader specifically designed to parse the Google News Feed. You can view and test the code on this Fiddle. My main challenge lies in removing titles and sources from the descriptions. Through my explorati ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

How to Send a JavaScript Array to a JSP Endpoint

I'm in the process of creating a web application that interacts with another website through a JS API. I would like to incorporate an array of JSON objects obtained from this API into my Java Application. Is there any way to submit this array, perhap ...

Tips on implementing a function within a navigation bar from a specific context

While working with a user authenticated context, I encountered an issue with the logout function. My goal is to have a link in the navigation bar that triggers the logout function and redirects me to the home page. However, I'm receiving a Typerror: l ...

We regret to inform you that the request cannot be processed by our Express

Currently, I am in the process of learning nodejs and expressjs and attempting to integrate it into the Spring MVC pattern. My intention behind this is to maintain cohesion within my files. However, the results are not quite aligning with my expectations.. ...

Utilize regular expressions in TamperMonkey to extract specific groups of text

I'm currently working on a TamperMonkey userscript that aims to identify URLs matching a specific pattern, visit these pages, extract relevant information, and then update the link for each URL with the extracted text. I'm facing some challenges ...

How can we add up the sum with just one click and then display the

Is there a way to calculate numbers within specific DIV boxes and display the total in a separate DIV when a box is clicked? I've attempted different methods, including enclosing the code within the window.onclick function. Check out my code on this J ...

reversed json using javascript

Is it possible to efficiently reverse the order of the following JSON object: { "10": "..." "11": "...", "12": "...", "13": "...", "14": "...", } so that it becomes: { "14": "...", "13": "...", "12": "...", "11": "... ...

What is the correct way to use variables to reference whether an item is odd or even in an ng-repeat loop?

Is there a way to access the variables $odd and $even within ng-repeat using a variable for reference? Here is what I have attempted: <ng-repeat="item in items" ng-if="$odd">these are odd{{item}}</div> <ng-repeat="item in items" ng-if="$eve ...

The images on the carousel fail to load unless I adjust the window size

After investing countless hours into finding a solution, I am still unable to resolve this issue. The problem lies within my use of a Carousel and setting the images through a javascript file. Strangely enough, upon loading the page, only the first image ...

Executing Ajax requests to interact with a RESTful API

After developing a back end REST API using Slim Framework and closely following the REST format, I ran into an issue when working on the Front End. It seems that AJAX functions well with parameters but not paths. I am considering outsourcing or creating a ...

Invoking PHP function within a specific class using Ajax

I am currently utilizing Zend Framework. My PHP class is structured as follows: FileName : AdminController.php Path : /admin/AdminController.php Ajax Function : function exportToExcel() { $.ajax({ url: "/admin/AdminController/testFunction", ty ...

Exploring file writing using Node Webkit and JavaScript

When developing my app, I encountered an issue with the 'fs' module not functioning as expected. Despite the code being written to write a file, nothing happens when the app is launched. However, if I start the app using the following command: $ ...

Can a dynamic title be implemented in a navbar?

On my website, I currently have a title navbar that is displayed on every page (TheNavbar Component). However, I want to dynamically change the title based on the specific page being viewed. For example, within my projects folder there is another folder ...

Creating the x and y coordinates for drawImage in HTML5

Understanding the x and y axis has posed a challenge for me: //retrieve last known x and y coordinates ...code var p = $("#draggable"); var offset = p.offset(); var x = offset.left; var y = offset.top; //establish new font siz ...

Are asynchronous promises thenable for chaining?

Can someone explain to me how asynchronous chaining works with thenable? I am new to using promises in Node.js and I am a bit confused about the concept. In the code example provided below, it seems like the promise returned from the previous Promise.the ...

Tips for eliminating flutter for static menu with easyResponsiveTabs.js

Experiencing a flickering issue with the fixed menubar and easyResponsiveTabs.js in my project when scrolling down. Attempted to resolve it using jquery.noConflict(), but without success. Would appreciate any guidance on how to address this problem. ...