Vue2监听复杂对象新旧值相同问题
记录下今天做项目时遇到的问题
功能需求: 销售属性 select 选中属性并点击右边添加销售属性按钮后,下方的 table 中新增刚才选中的 销售属性,同时让该行的 input 聚焦
页面html结构:
<el-table-column label="属性值名称列表" prop="spuSaleAttrValueList"> <template slot-scope="scope"> <el-tag closable size="small" @close="_deletSaleAttrValue(attrValue, scope.$index)" v-for="(attrValue, index) in scope.row.spuSaleAttrValueList" :key="attrValue.id" style="margin: 5px 10px" > {{attrValue.saleAttrValueName}} </el-tag> <!-- 添加属性值输入框 --> <el-input :ref="scope.$index" v-model.trim="saleAttrValueName" v-show="SpuInfo.spuSaleAttrList[scope.$index].flag" style="width: 180px" placeholder="请输入属性值" @blur="_handleBlurOrEnetr(scope)" @keyup.enter.native="$event.target.blur"> </el-input> <el-button v-show="!SpuInfo.spuSaleAttrList[scope.$index].flag" si***i" @click="_addSaleAttrValue(scope.$index)">添加</el-button> </template> </el-table-column>
data 中表单数据 SpuInfo 结构
解决思路:一开始直接想到监听 SpuInfo.saleAttrList 的数组长度(新旧值)的变化来让这个输入框聚焦 ( 只要该数组的长度变了,就执行 this.$refs[this.SpuInfo.saleAttrList.length -1].focus() )
现实给了我当头一棒,复杂数据类型变量存放的是值的引用,所以监听后那个数组新旧值都是一样的
最终解决方案:搞个计算属性计算出 SpuInfo 转换为字符串类型,在监听这个计算属性的变化