0

I have this 3 components in VueJS. The problem i want to solve is: When i click at vehicle component, it needs to be selected (selected = true) and other vehicles unselected. What i need to do for two-way data binding? Because i'm changing this selected property in VehiclesList.vue component and it also need to be changed in Monit.vue (which is a parent) and 'Vehicle.vue' need to watch this property for change class.

Also problem is with updating vehicles. In Monit.vue i do not update full object like this.vehicles = response.vehicles, but i do each by each one, and changing only monit property.

Maybe easier would be use a store for this. But i want to do this in components.

EDITED:Data sctructure

 {
   "m":[
      {
         "id":"v19",
         "regno":"ATECH DOBLO",
         "dt":"2017-10-09 13:19:01",
         "lon":17.96442604,
         "lat":50.66988373,
         "v":0,
         "th":0,
         "r":0,
         "g":28,
         "s":"3",
         "pow":1
      },
      {
         "id":"v20",
         "regno":"ATECH DUCATO_2",
         "dt":"2017-10-10 01:00:03",
         "lon":17.96442604,
         "lat":50.6698494,
         "v":0,
         "th":0,
         "r":0,
         "g":20,
         "s":"3"
      },
   ]
}

Monit.vue

<template>
  <div class="module-container">
      <div class="module-container-widgets">
        <vehicles-list :vehicles="vehicles"></vehicles-list>
      </div>
  </div>
</template>
<script>
import VehiclesList from '@/components/modules/monit/VehiclesList.vue';

export default {
  name: "Monit",
  data (){
      return {
          vehicles: null
      }
  },
  components: {
    VehiclesList
  },

  methods: {
    getMonitData(opt){
        let self = this;

        if (this.getMonitDataTimer) clearTimeout(this.getMonitDataTimer);

        this.axios({
            url:'/monit',
          })
          .then(res => {
                let data = res.data;
                console.log(data);
                if (!data.err){
                    self.updateVehicles(data.m);
                }

                self.getMonitDataTimer = setTimeout(()=>{
                    self.getMonitData();
                }, self.getMonitDataDelay);

              })
          .catch(error => {

          })
    },
    updateVehicles(data){
        let self = this;
        if (!this.vehicles){
            this.vehicles = {};
            data.forEach((v,id) => {
                self.vehicles[v.id] = {
                    monit: v,
                    no: Object.keys(self.vehicles).length + 1
                }
            });
        } else {
            data.forEach((v,id) => {
                if (self.vehicles[v.id]) {
                    self.vehicles[v.id].monit = v;
                } else {
                    self.vehicles[v.id] = {
                        monit: v,
                        no: Object.keys(self.vehicles).length + 1
                    }
                }
            });
        }
    },
  },
  mounted: function(){
     this.getMonitData();
  }
};
</script>

VehiclesList.vue

<template>
  <div class="vehicles-list" :class="{'vehicles-list--short': isShort}">
      <ul>
          <vehicle 
                v-for="v in vehicles" 
                :key="v.id" 
                :data="v"
                @click.native="select(v)"
          ></vehicle>
      </ul>
  </div>
</template>
<script>
import Vehicle from '@/components/modules/monit/VehiclesListItem.vue';

export default {
    data: function(){
        return {
            isShort: true
        }
    }, 
    props:{
        vehicles: {}
    },
    methods:{
        select(vehicle){
            let id = vehicle.monit.id;
            console.log("Select vehicle: " + id);
            _.forEach((v, id) => {
                v.selected = false;
            });
            this.vehicles[id].selected = true;
        }
    },
    components:{
        Vehicle
    }
}
</script>

Vehicle.vue

<template>
  <li class="vehicle" :id="data.id" :class="classes">
      <div class="vehicle-info">
        <div class="vehicle-info--regno font-weight-bold"><span class="vehicle-info--no">{{data.no}}.</span> {{ data.monit.regno }}</div>
      </div>
      <div class="vehicle-stats">
          <div v-if="data.monit.v !== 'undefined'" class="vehicle-stat--speed" data-name="speed"><i class="mdi mdi-speedometer"></i>{{ data.monit.v }} km/h</div>
      </div>

  </li>
</template>
<script>
export default {
    props:{
        data: Object
    },
    computed:{
        classes (){
           return {
               'vehicle--selected': this.data.selected
           }
        }
    }
}
</script>
Skodsgn
  • 940
  • 1
  • 10
  • 33

1 Answers1

1

Two-way component data binding was deprecated in VueJS 2.0 for a more event-driven model: https://v2.vuejs.org/v2/guide/components.html#One-Way-Data-Flow

This means, that changes made in the parent are still propagated to the child component (one-way). Changes you make inside the child component need to be explicitly send back to the parent via custom events: https://v2.vuejs.org/v2/guide/components.html#Custom-Events or in 2.3.0+ the sync keyword: https://v2.vuejs.org/v2/guide/components.html#sync-Modifier

EDIT Alternative (maybe better) approach:

Monit.vue:

<template>
  <div class="module-container">
      <div class="module-container-widgets">
        <vehicles-list :vehicles="vehicles" v-on:vehicleSelected="onVehicleSelected"></vehicles-list>
      </div>
  </div>
</template>
<script>
import VehiclesList from '@/components/modules/monit/VehiclesList.vue';

export default {
  name: "Monit",
  data (){
      return {
          vehicles: null
      }
  },
  components: {
    VehiclesList
  },

  methods: {
      onVehicleSelected: function (id) {
          _.forEach((v, id) => {
              v.selected = false;
          });
          this.vehicles[id].selected = true;
      }
      ...other methods
  },
  mounted: function(){
     this.getMonitData();
  }
};
</script>

VehicleList.vue:

methods:{
    select(vehicle){
        this.$emit('vehicleSelected', vehicle.monit.id)
    }
},

Original post: For your example this would probably mean that you need to emit changes inside the select method and you need to use some sort of mutable object inside the VehicleList.vue:

export default {
    data: function(){
        return {
            isShort: true,
            mutableVehicles: {}
        }
    }, 
    props:{
        vehicles: {}
    },
    methods:{
        select(vehicle){
            let id = vehicle.monit.id;
            console.log("Select vehicle: " + id);
            _.forEach((v, id) => {
                v.selected = false;
            });
            this.mutableVehicles[id].selected = true;
            this.$emit('update:vehicles', this.mutableVehicles);
        },
        vehilcesLoaded () {
            // Call this function from the parent once the data was loaded from the api. 
            // This ensures that we don't overwrite the child data with data from the parent when something changes.
            // But still have the up-to-date data from the api
            this.mutableVehilces = this.vehicles
        }
    },
    components:{
        Vehicle
    }
}

Monit.vue

<template>
  <div class="module-container">
      <div class="module-container-widgets">
        <vehicles-list :vehicles.sync="vehicles"></vehicles-list>
      </div>
  </div>
</template>
<script>

You still should maybe think more about responsibilities. Shouldn't the VehicleList.vue component be responsible for loading and managing the vehicles? This probably would make thinks a bit easier.

EDIT 2: Try to $set the inner object and see if this helps:

self.$set(self.vehicles, v.id, {
    monit: v,
    no: Object.keys(self.vehicles).length + 1,
    selected: false
});
tony19
  • 125,647
  • 18
  • 229
  • 307
puelo
  • 5,464
  • 2
  • 34
  • 62
  • I need `Monit.vue` for managing `vehicles` because i will have some more components in it to manipulating `vehicles`, like Maps, Tables etc – Skodsgn Feb 02 '18 at 13:06
  • Alright. I have a added an alternative solution, which requires less overhead and seems to be better fitted for this problem. – puelo Feb 02 '18 at 13:12
  • Event for changing `selected` is working. But `Vehicle.vue` component isn't listening this property – Skodsgn Feb 02 '18 at 13:39
  • Does the `selected` property exist when you get the data from the api? It should be reactive then. – puelo Feb 02 '18 at 13:52
  • Even if i update vehicles from api in `Monit.vue` with new data, nothing happen. – Skodsgn Feb 02 '18 at 15:32
  • Can you post the result from the api? It would also be best to console.log the vehicles object in each component and check if they are reactive objects. – puelo Feb 02 '18 at 16:12
  • I edited API result. It's looks like they are not reactive – Skodsgn Feb 02 '18 at 16:22
  • Please check if my latest edit does work/make the objects reactive. Every attribute you add at later stages need to be $set to be made reactive. See here: https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats – puelo Feb 02 '18 at 16:29
  • It's working now. Also working something like `this.vehicles = newVehicles`, when i create clone of `this.vehicles` and assign new values to it Thanks :) – Skodsgn Feb 02 '18 at 16:50