Building a dynamic attribute management system with vue and vuetify

In the backend business object, there is a custom attributes data structure that allows clients to add key/value pairs for storing in the database. For instance:

Map<String, String> customAttributes;

Here's an example of how it would look in the user interface (with the option to add more rows): https://i.sstatic.net/G5pfD.png

Inside the vue's data function, I have set a placeholder for this data:

data() {
    return {
      customAttributes: {},
      ...
    }

However, I am struggling to find a way to connect the UI inputs to the customAttributes object so that adding a new row (attribute) automatically adds a corresponding key and value to it.

Is there a different approach I could take to handle this situation?

Answer №1

Using a Map may not be the best choice in Vue, as object keys that can easily be modified can cause tracking issues. It would be more suitable to utilize something like

Array<{ key: string, value: string }>

If you really require the map version, it can still be derived from the array quite easily.

const model = { key: "", value: "" }

new Vue({
  el: "#app",
  data: () => ({
    attributes: [{
      key: "GRADLE_HOME",
      value: "/usr/local/gradle"
    }, {
      key: "JAVA_HOME",
      value: "/usr/lib/jvm/whatever"
    }]
  }),
  computed: {
    attributeMap: ({ attributes }) =>
      Object.fromEntries(attributes.map(({ key, value }) => [ key, value ]))
  },
  methods: {
    add () {
      this.attributes.push({...model})
    },
    del (index) {
      this.attributes.splice(index, 1)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <table border="1">
    <thead><tr><th>Name</th><th>Value</th></tr></thead>
    <tbody>
      <tr v-for="(attr, index) in attributes" :key="index">
        <td><input v-model="attr.key"/></td>
        <td>
          <input v-model="attr.value" />
          <button @click="del(index)">&times;</button>
        </td>
      </tr>
    </tbody>
    <tfoot>
      <tr><td colspan="2"><button @click="add">Add Attribute</button></td></tr>
    </tfoot>
  </table>
  <pre>attributeMap = {{ attributeMap }}</pre>
</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

What are the steps to manually activate input validation in Angular 2?

Having two inputs is the scenario here: The first input undergoes custom validator application The second input has a dynamic and editable value utilized in the custom validator If the custom validator is applied on the first input, then focus shifts to ...

What is the best method for testing different versions of the same module simultaneously?

My goal is to distribute a module across various component manager systems like npmjs and bower. I also want to provide downloadable builds in different styles such as AMD for requirejs, commonJS, and a global namespace version for browsers - all minified. ...

How to Filter, Sort, and Display Distinct Records in an HTML Table with jQuery, JavaScript, and

In the HTML page, there will be a total of 6 tabs labeled A, B, C, D, E, and F along with 2 dropdowns. The expected behavior is as follows: The user will choose a value from the 2 dropdown menus. Based on the selected value, filtering should be applied to ...

Vue filter and the importance of not modifying the vuex store state without using mutation handlers

Learning Vue is an ongoing journey for me, but I'm struggling to grasp why this particular error keeps popping up. Error: [vuex] Do not mutate vuex store state outside mutation handlers. Let's take a look at the code snippet in question: ...

Issue with specific route causing server to throw 500 error

Recently, I have been working on a small school project that involves creating our own API and connecting it to an Angular front end. While following some tutorials, I encountered an issue where my application started throwing internal server error 500 af ...

Is it considered fashionable to utilize HTML5 data attributes in conjunction with JavaScript?

Currently, I am utilizing HTML5 data attributes to save information such as the targeted DOM element and to initialize events using jQuery's delegation method. An example of this would be: <a href="#" data-target="#target" data-action="/update"> ...

Add a variety of parameters to the URL in order to make an AJAX request

I want to dynamically add values from checked checkboxes to a URL for use in an AJAX call. I only want these values to be added to the URL if the checkbox is checked. If a user checks and then unchecks, I do not want that value included in the URL. Below ...

Some PDF files appear as blank when shown using a Base64 encoded string

I am attempting to display a PDF file on a web page using its base64 encoding. Below is the ReactJS code I am using: <object style={{ width: '100%', height:'842pt' }} type="application/pdf" data={`data:application/pdf;base ...

Developing a custom function to retrieve an array as a callback

I'm currently diving into the world of Node.js Struggling with implementing my own callback function in a certain method. It may seem like a straightforward task, but I'm finding it quite challenging to grasp. This specific function takes an ad ...

What is the technique for causing this element to move in reverse?

How can I utilize JS to halt the interval and direct the alien to move backwards once it reaches 700px? I am aware that CSS can achieve this, but I prefer a strictly JS approach. I am struggling with stopping the interval as it hits the left position of 70 ...

Getting query parameter with hyphen in nextJS 13 - step by step tutorial

One of the challenges I am facing involves accessing a query parameter with a hyphen in its name within a route: /?previous-page=building-details Within my Page component: import EnergyEfficiency from "@/ui/energy-check/energy-efficiency" cons ...

AngularJS encounters bad configuration on 'GET' request

I am facing an issue with my API that returns data to AngularJS based on a given ID. When the data is returned as JSON, AngularJS throws a 'badcfg' error, indicating that it could be due to the format of the returned data. I'm struggling to ...

Prevent dropzone from refreshing the page

For the past few days, I have been scouring the internet for solutions on how to prevent a page from automatically reloading after an upload. Despite finding various methods, I have been unsuccessful in resolving this issue. Although I am following the st ...

What steps should be taken to create a two-column table from a given list of items?

I am trying to display a list of words in two columns, one word after another from left to right. Here is the desired table structure: <table id="wordTable"> <tr> <td>ac </td> <td>bd </td> </tr> ...

Tips for showcasing information from firebase using the vis.js timeline widget

Hello there! I am currently working with the vis.js timeline library and I am trying to display dates from a Firestore database. Interestingly, it works perfectly fine when I manually type in the data (refer to this.items), but unfortunately does not wor ...

Using HTML to execute a JavaScript function that transforms images

The script cutImageUp has been previously discussed on SE in a thread about Shattering image using canvas. However, I have encountered a different issue while attempting to use it. The HTML code I implemented seems to be ineffective, and despite my efforts ...

What are the steps to implement character movement in a 2D game using JavaScript?

I'm having trouble getting the image with the ID "yoshi" to move around in my 2D game document.onkeydown = (e) => { if (e.keyCode == 37) yoshi.style.left = yoshi.offsetLeft - 5 + "px"; else if (e.keyCode == 38) yoshi.style.top = yoshi.offset ...

When the user clicks, I plan to switch the audio source

I am looking to update the audio source when a button is clicked, but I am having trouble getting it to work. image description data() { return { audioSrc: '' } }, methods: { setActiveAudio(item) { this.$refs.audioE ...

Bootstrap Table Vue Selection

When I attempt to use the data provided below, the first column shows as true/false instead of a checkbox. Below is the Vue table code: <b-table id="myTabel" hover striped :items="tableData" :fields="tableColumns"> <template slot="selected" sl ...

What is the best way to toggle the color of the circle div in the center between yellow and white with every click within the circle?

Up to now, I have successfully accomplished this with just one click. I deleted the lightbulb image const sphere = document.getElementById("sphere"); sphere.addEventListener("click", event => { console.log("You clicked the ...