VueJs观察对象的深刻变化

时间:2018-02-02 12:19:53

标签: javascript css html5 vue.js

我在VueJS中有这3个组件。我想解决的问题是:当我点击vehicle组件时,需要选择它(selected = true)并取消选择其他车辆。 我需要做什么才能进行双向数据绑定?因为我正在更改selected组件中的VehiclesList.vue属性,并且还需要在Monit.vue(父级)中更改,而“Vehicle.vue”需要查看此属性改变班级。

还有问题是更新车辆。在Monit.vue中,我不更新this.vehicles = response.vehicles之类的完整对象,但是每个都会更新每个对象,并且只更改monit属性。

也许更容易使用商店。但我想在组件中这样做。

已编辑:数据结构

 {
   "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>

1 个答案:

答案 0 :(得分:1)

在VueJS 2.0中不推荐使用双向组件数据绑定,以获得更多事件驱动的模型:https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow

这意味着,在父级中所做的更改仍会传播到子组件(单向)。您在子组件中所做的更改需要通过自定义事件显式发送回父级:https://vuejs.org/v2/guide/components.html#Custom-Events或2.3.0+ sync关键字:https://vuejs.org/v2/guide/components.html#sync-Modifier

EDIT替代(可能更好)方法:

<强> 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)
    }
},

原帖: 对于您的示例,这可能意味着您需要在select方法中发出更改,并且您需要在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>

你仍然应该更多地考虑责任。 VehicleList.vue组件不应该负责装载和管理车辆吗?这可能会使思考变得容易一些。

编辑2: 尝试$set内部对象,看看这是否有帮助:

self.$set(self.vehicles, v.id, {
    monit: v,
    no: Object.keys(self.vehicles).length + 1,
    selected: false
});