Javascript 当对象属性更改时,如何在vue js中获取对象索引?

Javascript 当对象属性更改时,如何在vue js中获取对象索引?,javascript,vue.js,Javascript,Vue.js,我的vue组件代码如下所示 data: function () { return { products: [ { product_id: '', price: ''}, { product_id: '', price: ''}, ], } }, 现在我想在v-model=product\u id发生变化时获取对象索引。有什么解决办法吗 <div v-for="(product,

我的vue组件代码如下所示

data: function () {
    return {   
        products: [ 
            { product_id: '', price: ''}, 
            { product_id: '', price: ''},  
        ],
    }
},
现在我想在v-model=product\u id发生变化时获取对象索引。有什么解决办法吗

<div v-for="(product, key) in products">
    <input type="text" v-model="product.product_id" />
    <input type="text" v-model="product.price" />
</div><!--  /.div -->
谢谢阅读以下内容:

请阅读以下内容:


您可以将手表与以下部件配合使用:

watch: {
   'products.product': {
       handler(newValue, oldValue) {
           // make sure it changed
           if(newValue != oldValue) {
              // get the row that changed
              let [rowChanged] = _.difference(newValue, oldValue);
              // find its index
              let arrayIndex = newValue.indexOf(rowChanged);
           }  
       },
       deep: true
   }
}

这样的办法应该行得通。如果您愿意,您可以将所有内容组合到一个JSFIDLE中,这样我们就可以看到整个.vue组件。

您可以将手表与以下内容结合使用:

watch: {
   'products.product': {
       handler(newValue, oldValue) {
           // make sure it changed
           if(newValue != oldValue) {
              // get the row that changed
              let [rowChanged] = _.difference(newValue, oldValue);
              // find its index
              let arrayIndex = newValue.indexOf(rowChanged);
           }  
       },
       deep: true
   }
}

这样的办法应该行得通。如果您愿意,您可以将所有内容组合到一个JSFIDLE中,这样我们就可以看到整个.vue组件。

为什么不添加一些在@change event上触发的方法呢

新Vue{ el:应用程序, 数据:{ 待办事项:[ {text:'学习JavaScript'}, {text:'Learn Vue'}, {text:'Play-around-in-JSFiddle'}, {text:'构建一些很棒的东西'} ] }, 方法:{ getIndexindex{ console.logindex } } }
为什么不添加一些在@change事件上触发的方法呢

新Vue{ el:应用程序, 数据:{ 待办事项:[ {text:'学习JavaScript'}, {text:'Learn Vue'}, {text:'Play-around-in-JSFiddle'}, {text:'构建一些很棒的东西'} ] }, 方法:{ getIndexindex{ console.logindex } } }
你所说的数组对象索引是什么意思?你可以使用watch,带有deep:true,你不需要索引,你有实际的对象引用。但是,如果您想要索引,只需使用Array.findIndex或lodash的等效项即可。@HarshPatel如果第一个产品id发生更改,则希望得到0索引。如果第二个产品的id发生了更改,则1@ZachLeighton你能给我演示代码吗?你说的数组对象索引是什么意思?你可以使用watch,带有deep:true,你不需要索引,你有实际的对象引用。但是,如果您想要索引,只需使用Array.findIndex或lodash的等效项即可。@HarshPatel如果第一个产品id发生更改,则希望得到0索引。如果第二个产品的id发生了更改,则1@ZachLeighton你能给我演示代码吗?我想让它像Vue watch一样自动运行:{}。当v-model=product\u id发生变化时,我对这个混乱的问题感到抱歉。我已经创建了一个新的,请看,我想让它像Vue手表一样自动:{}。当v-model=product\u id发生变化时,我对这个混乱的问题感到抱歉。我已经创建了一个新的,请在v-model=todo.text字段中查看。我正在使用多选择器字段组件,无法在此字段中传递额外参数。我已经创建了一个问题,请查看@RakibulHasan,然后用该信息更新您的OP。如果你能创建一个插件也很好。很抱歉这个问题很麻烦。我已经创建了一个新的,请在v-model=todo.text字段中查看。我正在使用多选择器字段组件,无法在此字段中传递额外参数。我已经创建了一个问题,请查看@RakibulHasan,然后用该信息更新您的OP。如果你能创建一个插件也很好。很抱歉这个问题很麻烦。我已经创建了一个新值请查看我不确定watch是否是正确的方法,因为它有一个警告:注意:当进行变异而不是替换对象或数组时,旧值将与新值相同,因为它们引用相同的对象/数组。Vue没有保留预变异值的副本。我不确定watch是否是正确的方法,因为它有一个警告:注意:当变异而不是替换对象或数组时,旧值将与新值相同,因为它们引用相同的对象/数组。Vue不保留预变异值的副本。