Vue observers fire on data() changes
P粉144705065
P粉144705065 2024-03-26 09:06:45
0
1
430

<script>
export default {
  name: "DriversStandings",

  data() {
    return {
      standingsData: [],
    };
  },

  props: ["drivers", "isUpdated"],

  watch: {
    drivers: {
      deep: true,
      handler: function () {
        this.test();
      },
    },
  },

  methods:{
    test(){
      console.log("chamou o teste")
      this.standingsData = this.drivers
    }
  }
};
</script>

I'm a little crazy. Shouldn't the observer only observe the "driver" prop? When I edit "standsData" it also triggers in a way that prevents me from sorting it. Did I miss something?

P粉144705065
P粉144705065

reply all(1)
P粉662802882

This may depend on how you sort the array, but since you assigned this.standsData = this.drivers, any variations on this.standsData Changes will also mutate the data under this.drivers because they reference the same array. You may want to copy the driver array to put in the component state like this:

  methods: {
    test() {
      console.log("chamou o teste")
      this.standingsData = [...this.drivers];
    }
  }

Keep in mind that similar issues will arise when deeply modifying other data in this.standsData because you specify deep: true on the observer; if you must Do, you will need to deeply copy the data when moving this.drivers to this.standsData. This can be done using custom code or tools like lodash.cloneDeep.

Another quirk here is that, by default, Vue observers are not fired on component initialization. If you want it to be triggered when the drivers property changes when it is initially set during component initialization, you need to add immediate: true to the watcher (docs here).

  watch: {
    drivers: {
      deep: true,
      immediate: true,
      handler: function () {
        this.test();
      },
    },
  },
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template