<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粉6628028822024-03-27 00:58:01
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(); }, }, },