一、错误代码:
<div class="el-form-item"> <label for="region" class="el-form-item__label" style="width: 80px;">选择商品</label> <div class="el-form-item__content" style="margin-left: 80px;"> <el-select v-model="shopObj.id" placeholder="请选择" style="width:100%;"> <el-option @click.native="selectShopChange(item)" v-for="item in shopList" :key="item.id" :label="item.name" :value="item.id"> </el-option> </el-select> </div> </div> <script type="text/javascript"> new Vue({ el: '#main', data: function() { return { shopList: [], shopObj: [], }, methods: { selectShopChange(item) { this.shopObj = item; this.paytypeChange(this.paytype); }, } }); </script>
上述代码中,el-select是直接绑定整个商品对象shopObj,会导致切换选项时,唯一的id没有成功更新,会出现两个被选中的商品,如下图:
二、正确代码:
<div class="el-form-item"> <label for="region" class="el-form-item__label" style="width: 80px;"> 选择商品 </label> <div class="el-form-item__content" style="margin-left: 80px;"> <el-select v-model="shopid" placeholder="请选择" style="width:100%;" clearable @change="$forceUpdate()"> <el-option @click.native="selectShopChange(item)" v-for="item in shopList" :key="item.id" :label="item.name" :value="item.id"> </el-option> </el-select> </div> </div> <script type="text/javascript"> new Vue({ el: '#main', data: function() { return { shopList: [], shopid:0, shopObj: [], }, methods: { selectShopChange(item) { this.shopid = item.id; this.shopObj = item; this.paytypeChange(this.paytype); }, } }); </script>
上述代码绑定的是一个独立的shopid变量,这样能保证el-select选中的值永远是唯一的,效果如下:
请登录之后再进行评论