简体   繁体   English

vue.js中的动态v模型

[英]Dynamic v-model in vue.js

Can someone help me generate dynamic v-model values? 有人可以帮助我生成动态v模型值吗?

<div v-for="car in cars">
  <div class="row">
    <div class="col-md-2">
      <p v-model="car.attr_1">{{ car.attr_1 }}</p>
    </div>
    <div class="col-md-3">
      <p v-model="car.attr_2">{{ car.attr_2 }}</p>
    </div>
    <div class="col-md-2">
      <p v-model="car.attr_3">$ {{ car.attr_3 }}</p>
    </div>
    <div class="col-md-2">
      <p><input type="text" class="" placeholder="Quantity" v-on:click="addCar(car)"/></p>
    </div>
  </div>
</div> 


<script>

module.exports = {

  data: function () {
    return {
      cars: ''
    }
  },

  methods: {

    getCars: function () {

      var self = this;

      $.ajax({
        type: "GET",
        url: '/api/cars',
        success: function(data) {
          self.cars = data;
        }
      });
    }
  }
}

</script>

Sample JSON response - note how all the properties are different..: 样本JSON响应-注意所有属性如何不同..:

cars: [

  {
    make: 'Audi',
    model: 'R8',
    color: 'red'
  },

  {
    make: 'Chevy',
    tires: 'All Season',
    weight: 30
  },

  {
    make: 'Chevy',
    tires: 'Summer',
    color: 'black'
  },

  {
    make: 'Ford',
    weight: 40,
    gps: true
  }


]

I have an ajax call that returns an array of cars objects. 我有一个ajax调用,该调用返回一个cars对象数组。 The problem is all the objects returned have variable attributes. 问题是所有返回的对象都具有变量属性。 Therefore, how can vue.js handle these variable attributes for v-model? 因此,vue.js如何处理v模型的这些变量属性? I've tried things like v-model="car[ {{attr_1}} ]" but these all return errors.. Can someone help? 我已经尝试过类似v-model="car[ {{attr_1}} ]"但是这些都返回错误。.有人可以帮忙吗?

Thanks in advance! 提前致谢!

You can do it something like: 您可以执行以下操作:

<div v-for="car in cars">
  <div class="row">
    <div class="col-md-2" v-if="car.make">
      <p v-model="car.make">{{ car.make }}</p>
    </div>
    <div class="col-md-3" v-if="car.tires">
      <p v-model="car.tires">{{ car.tires }}</p>
    </div>
    <div class="col-md-2" v-if="car.color">
      <p v-model="car.color">$ {{ car.color }}</p>
    </div>
    <div class="col-md-2">
      <p><input type="text" class="" placeholder="Quantity" v-on:click="addCar(car)"/></p>
    </div>
  </div>
</div> 

alternatively, You can also write a method, which given car object and attribute, will return corresponding value: 或者,您也可以编写一个方法,该方法给定的car对象和属性将返回相应的值:

function(car, attr){
  return car[attr];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM