Search code examples
vue.jsdata-bindingvue-componentdynamic-programmingcss-tables

Vuejs - Get dynamically generated input field and its value and change its color on change


In Vue.js I have created a table with editable fields. The table fields are dynamically generated like:

   <b-table :items="filtered" :fields="columns">
      <template v-for="field in editableFields" v-slot:[tableCell(field.key)]="{ item }">
        <b-form-input  v-model="item[field.key]" v-bind:key="field.key""/>
      </template>
    </b-table>

The v-slot method is this:

tableCell(fieldkey) {
  return `cell(${fieldkey})`;
}

That part is working juts fine :-)

My problem is that I would like to color a changed input field value and keep track of its value, so if its value changes back to the default, then the color defaults back to the original color. Like:

|_hello _|_default _|_input _|
|____|____|____|

|_hello _|_color _|_input _|
|______|_______|______|

So the value "default" is not colored, and when changed to "color" the input field chould be colored red. When changing back to "default" the color should be reset.

The "item[field.key]" is representing each og the table cell values: "hello", "default", "input", "color" etc.

I've tried looking into "v-bind:class {active: active}" and v-on:change(item[field.key]) and Vues Watch, but I just can't find the way..

Thanks in regards


Solution

  • I've made a quick demo, showing how to apply a css class when the value is different.

    I hope this helps.

    .changed {
       background-color: orange;
       color: white;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
    <input type="text" :class="{ changed : oldValue !== newValue }" v-model="newValue" />
    </div>
    
    <script>
    new Vue({
      el: '#app',
      data: function() {
        return {
          oldValue: "Hello",
          newValue: "Hello"
        }
      }
    })
    </script>