Vue - 深入观察对象数组并计算变化? [英] Vue - Deep watching an array of objects and calculating the change?

查看:26
本文介绍了Vue - 深入观察对象数组并计算变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 people 的数组,它包含如下对象:

I have an array called people that contains objects as follows:

之前

它可以改变:

之后

注意弗兰克刚满 33 岁.

After

我有一个应用程序,我试图在其中观察 people 数组,当任何值发生更改时,请记录更改:

[ {id: 0, name: 'Bob', age: 27}, {id: 1, name: 'Frank', age: 33}, {id: 2, name: 'Joe', age: 38} ]

Notice Frank just turned 33.

<脚本>新的 Vue({el: '#app',数据: {人们: [{id:0,姓名:'鲍勃',年龄:27},{id:1,姓名:'弗兰克',年龄:32},{id:2,姓名:'乔',年龄:38}]},手表: {人们: {处理程序:函数(val,oldval){//返回改变的对象var 改变 = val.filter( function( p, idx ) {返回 Object.keys(p).some( function( prop ) {返回 p[prop] !== oldVal[idx][prop];})})//记录它控制台日志(已更改)},深:真实}}})

I have an app where I am trying to watch the people array and when any of the values changes then log the change:

我基于 问题我昨天询问了关于数组比较的问题,并选择了最快的工作答案.

<style> input { display: block; } </style> <div id="app"> <input type="text" v-for="(person, index) in people" v-model="people[index].age" /> </div> <script> new Vue({ el: '#app', data: { people: [ {id: 0, name: 'Bob', age: 27}, {id: 1, name: 'Frank', age: 32}, {id: 2, name: 'Joe', age: 38} ] }, watch: { people: { handler: function (val, oldVal) { // Return the object that changed var changed = val.filter( function( p, idx ) { return Object.keys(p).some( function( prop ) { return p[prop] !== oldVal[idx][prop]; }) }) // Log it console.log(changed) }, deep: true } } }) </script>

所以,此时我希望看到的结果是:{ id: 1, name: 'Frank', age: 33 }

I based this on the question that I asked yesterday about array comparisons and selected the quickest working answer.

但我在控制台中得到的只是(记住我在一个组件中拥有它):

So, at this point I expect to see a result of: { id: 1, name: 'Frank', age: 33 }

But all I get back in the console is (bearing in mind i had it in a component): 

在我制作的 codepen 中,结果是一个空数组,而不是更改后的数组对象发生了变化,这正是我所期望的.

[Vue warn]: Error in watcher "people" (found in anonymous component - use the "name" option for better debugging messages.)

如果有人可以提出为什么会发生这种情况或我在这里出错的地方,那么将不胜感激,非常感谢!

And in the codepen that I made, the result is an empty array and not the changed object that changed which would be what I expected.

推荐答案

您的旧值和新值之间的比较函数存在问题.最好不要把事情搞得太复杂,因为这会增加你以后的调试工作.你应该保持简单.

解决方案

最好的方法是创建一个person-component,并在其自己的组件内分别观察每个人,如下所示:

Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.

The best way is to create a person-component and watch every person separately inside its own component, as shown below:

请在下面找到一个用于观察内部人员组件的工作示例.如果你想在父端处理它,你可以使用$emit向上发送一个事件,包含被修改人的id.

<person-component :person="person" v-for="person in people"></person-component>



这篇关于Vue - 深入观察对象数组并计算变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆