如何通过单击 children 组件之一更新 Vue 组件数组
How to update Vue array of components with a click IN one of the children components
我正在显示 child 组件数组,在 child 组件中,我需要单击一些文本以使 THIS
child 推送到阵列。
我试过 child 看到的数组似乎没有任何帮助。现在我已经尝试向 parent 组件发出一个事件,但我似乎仍然无法弄清楚如何通过单击将任何 child 组件推到循环的开头IN
child 组件。
Parent 组件和方法:
<location-item v-for="(location, index) in results"
:key="location.Id"
:index="index"
:location="location"
@changeLocation="changeLocation(location, $event)" />
methods(): {
changeLocation(location, newIndex) {
location.index = newIndex;
},
}
Child 组件的可点击文本和方法
<a @click="changeCurrent">
Change Location
</a>
methods: {
changeCurrent() {
this.$emit('changeLocation', this.newIndex);
}
},
因此,当它在 child 组件中单击时,它会将 THAT
child 组件抛出到 v-for
循环的开头。我给出的建议是我所得到的最接近的建议,然而,它什么也没做。我还没有看到网上有人真的这样做,所以我想我会来这里问一下。
这是一个非常 JavaScript 的问题。从 child 发射到 parent,您走在正确的轨道上,需要使用 splice()
.
做一些 javascript
由于您已经将 child 组件的索引传递给组件,这是我们唯一需要传递给 parent 的内容,所以...
Child:
props: {
location: String,
index: Number,
},
methods: {
changeCurrent() { // pass the childs index to parent
this.$emit("change-location", this.index);
},
},
然后在 parent changeLocation
函数中我们使用索引重新排序数组:
changeLocation(index) {
let item = this.results.splice(index, 1); // remove item from array
this.results.splice(0, 0, item[0]); // put item first in array
},
这里有一个 DEMO 给你。您也可以使用 unshift
添加项目。
我正在显示 child 组件数组,在 child 组件中,我需要单击一些文本以使 THIS
child 推送到阵列。
我试过 child 看到的数组似乎没有任何帮助。现在我已经尝试向 parent 组件发出一个事件,但我似乎仍然无法弄清楚如何通过单击将任何 child 组件推到循环的开头IN
child 组件。
Parent 组件和方法:
<location-item v-for="(location, index) in results"
:key="location.Id"
:index="index"
:location="location"
@changeLocation="changeLocation(location, $event)" />
methods(): {
changeLocation(location, newIndex) {
location.index = newIndex;
},
}
Child 组件的可点击文本和方法
<a @click="changeCurrent">
Change Location
</a>
methods: {
changeCurrent() {
this.$emit('changeLocation', this.newIndex);
}
},
因此,当它在 child 组件中单击时,它会将 THAT
child 组件抛出到 v-for
循环的开头。我给出的建议是我所得到的最接近的建议,然而,它什么也没做。我还没有看到网上有人真的这样做,所以我想我会来这里问一下。
这是一个非常 JavaScript 的问题。从 child 发射到 parent,您走在正确的轨道上,需要使用 splice()
.
由于您已经将 child 组件的索引传递给组件,这是我们唯一需要传递给 parent 的内容,所以...
Child:
props: {
location: String,
index: Number,
},
methods: {
changeCurrent() { // pass the childs index to parent
this.$emit("change-location", this.index);
},
},
然后在 parent changeLocation
函数中我们使用索引重新排序数组:
changeLocation(index) {
let item = this.results.splice(index, 1); // remove item from array
this.results.splice(0, 0, item[0]); // put item first in array
},
这里有一个 DEMO 给你。您也可以使用 unshift
添加项目。