A
A
Andrey Shulepin2018-12-27 02:59:31
Vue.js
Andrey Shulepin, 2018-12-27 02:59:31

How to track field changes in a component to enable save buttons?

There are date fields, let's say 'name' and ''name_changed'.
It's under surveillance:

watch:{
  name(val, old){
    this.name_changed = true;
  }
}

and in the template there is a button for saving/sending the field value with :disabled="!name_changed", i.e. the button should initially be disabled, and after the value is changed by the user, it should be "disabled"
The name field is filled in by axios request (in the mounted method).
So, the problem is that apparently when the name field is filled on the first request, the name_changed field becomes true and the save button is initially available.
As an option, I should check somewhere when changing the name that it was the user who changed and not the program initiation.
Of course, you can hang a listener on input and hang your own logic, but it will come out all in the template, and this is somehow not beautiful. And in the working code there are a lot of tracked fields and there will be porridge in the template
I would like to turn everything as much as possible in JS.
Someone might have done this elegantly.
Sample code sketched in the comment below

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Myasin, 2018-12-27
@LisPNZ

Watchers are usually a hallmark of jailbreak =) It's
better to keep the original data and compare it with the current one. So the honest changed will be (you rather have "touched").
Here's roughly:

const api = {
  async getData() {
    return {name: 'Foo', email: '[email protected]'};
  }
}

new Vue({
  el:'#app',
  template: `<div v-if="current">
    <input v-model="current.name" />
    <input v-model="current.email" />
    <button :disabled="!isChanged">submit</button>
  </div>`,
  data() {
    return {
      original: null,
      current: null,
    }
  },
  async created() {
    const data = await api.getData();
    this.original = JSON.stringify(data);
    this.current = data;
  },
  computed: {
    isChanged() {
      return JSON.stringify(this.current) !== this.original;
    }
  }
});

https://codepen.io/dubrowsky/pen/BvdKZE?editors=1010
UPD: If you need not changed, but touched - do it
<input type="text" v-model="name" @input="name_changed = true">
and there will be happiness

0
0xD34F, 2018-12-27
@0xD34F Vue.js

the problem is that apparently when the name field is filled on the first request, accordingly the name_changed field becomes true and the save button is initially available

You can start tracking after receiving data. cut out
watch:{
  name(val, old){
    this.name_changed = true;
  }
}

And in the request callback, after setting the name value, add:
this.$watch('name', () => this.name_changed = true);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question