[Vuejs]-How to set the whole data property of component to a new object keeping reactivity in Vue?

1👍

I had a similar issue like this once. It is because (depending on how you are assigning the initial state) you are probably still observing the same object.

Try recreating the object that you want to assign on each assignment.

const emptyFilters = {
    name: ''
};

export default class MyComponent extends Vue {
    methods: {
        setFilters () {
            let filters = JSON.parse(JSON.stringify(emptyFilters));
            this.$set(this, 'filtersFields', filters);
        },
    },
};

2👍

As Jesus Galvan correctly points out, this is very likely caused by your initialization code. Let’s say you have the following template:

<template>
  <div>
    <input v-model="filtersFields.firstName" type="text" />
    <input v-model="filtersFields.lastName" type="text" />
    <button @click="onReset">reset</button>
  </div>
</template>

Here’s an example implementation that will not work:

const EMPTY_FILTERS = { firstName: '', lastName: '' };

export default {
  data() {
    return { filtersFields: EMPTY_FILTERS };
  },
  methods: {
    onReset() {
      this.filtersFields = EMPTY_FILTERS;
    },
  },
};

This fails because this.filtersFields = EMPTY_FILTERS actually does nothing. Object assignment in JS is done by reference, so filtersFields already points to EMPTY_FILTERS. Here’s an example that does work:

const EMPTY_FILTERS = { firstName: '', lastName: '' };

export default {
  data() {
    return { filtersFields: { ...EMPTY_FILTERS } };
  },
  methods: {
    onReset() {
      this.filtersFields = { ...EMPTY_FILTERS };
    },
  },
};

This time we are always assigning a copy of EMPTY_FILTERS, which will correctly be observed by Vue.

Leave a comment