2017-05-29 73 views
1

美好的一天,我正在与Vuejs进行简单的内联编辑功能。请看看这个jsbinvuejs内联编辑选择框选项呼叫问题

用户信息。与Edit按钮列出,当点击时,我把它们变成输入/选择字段,并用辅助方法填充相应的选项。

我的问题在这里有一次我填充选择选项,我的帮助方法被称为即使我改变选择值。我怎样才能改变它只加载一次并使用它们。另外,如何在点击save按钮时根据需要验证当前行字段?

回答

1

试试这个。

new Vue({ 
    el: '#app', 

    data: { 
     users: [ 
     {name: 'Jhon', city:'Newyork', country: 'US', country_id:'23', city_id:'4'}, 
     {name: 'Ali', city:'London', country: 'UK', country_id:'13', city_id:'33'}, 
     {name: 'Raj', city:'Delhi', country: 'IN', country_id:'3', city_id:'11'}, 
     ], 
     cities: [ 
      {id:'4', val:'Newyork', country_id:'23'}, 
      {id:'33', val:'London', country_id:'13'}, 
      {id:'11', val:'Delhi', country_id:'3'}, 
     ], 
     countries: [ 
      {id:'23', val:'US'}, 
      {id:'13', val:'UK'}, 
      {id:'3', val:'IN'}, 
     ] 

    }, 
    computed:{ 
     citiesByCountry(){ 
     return this.countries.reduce((acc, country) => { 
      acc[country.id] = this.cities.filter(c => c.country_id == country.id) 
      return acc 
     }, {}) 
     } 
    }, 
    methods: { 
     edit :function(obj){ 
     this.$set(obj, 'editmode', true); 
     }, 
     save : function(obj){ 
     this.$set(obj, 'editmode', false); 
     }, 
     cloneLast:function(){ 
     var lastObj = this.users[this.users.length-1]; 
     lastObj = JSON.parse(JSON.stringify(lastObj)); 
     lastObj.editmode = true; 
     this.users.push(lastObj); 
     }, 

    } 
    }) 

然后将您的模板更改为此。

<td> 
    <span v-if="user.editmode"> 
     <select v-model="user.city_id" required> 
     <option v-for="option in citiesByCountry[user.country_id]" :value="option.id">{{option.val}}</option> 
     </select> 
    </span> 
    <span v-else>{{user.city}}</span> 
    </td> 
    <td> 
    <span v-if="user.editmode"> 

     <select v-model="user.country_id" required> 
     <option v-for="option in countries" :value="option.id">{{option.val}}</option> 
     </select> 
    </span> 
    <span v-else>{{user.country}}</span> 
    </td> 

工作example

+0

谢谢你的建议。但是,实际上城市的选择取决于所选择的国家。它会发送一个Ajax请求到服务器获取城市列表。我不能将它们存储为静态对象。对不起,不清楚。 –

+0

@NareshRevoori然后使其成为一个计算。 – Bert

+0

请看看http://jsbin.com/vevivesena/edit?html,js,output –