我有什么:组件结构
<Games> // using v-for - iterate all games
--<Game> // using v-for - iterate all players
----<Player 1>
------<DeleteWithConfirmation>
----<Player 2>
------<DeleteWithConfirmation>
----<Player 3>
------<DeleteWithConfirmation>
----...
<DeleteWithConfirmation>
实现:删除游戏属性需要两次单击。
<template>
<div>
<button @click="incrementDelete"
v-html="deleteButtonHTML"></button>
<button v-if="deleteCounter === 1" @click="stopDeleting">
<i class="undo icon"></i>
</button>
</div>
</template>
<script>
export default {
name: 'DeleteWithConfirmation',
data() {
return {
deleteCounter: 0
}
},
computed: {
deleteButtonHTML: function () {
if (this.deleteCounter === 0)
return '<i class="trash icon"></i>'
else
return 'Are you sure?'
}
},
methods: {
incrementDelete() {
this.deleteCounter++
if (this.deleteCounter === 2) {
//tell parent component that deleting is confirmed.
//Parent call AJAX than.
this.$emit('deletingConfirmed')
this.stopDeleting()
}
else if (this.deleteCounter > 2)
this.stopDeleting()
},
stopDeleting() {
Object.assign(this.$data, this.$options.data())
}
}
}
</script>
我的问题:似乎指标混杂在一起:
在删除第四名玩家之前,它处于“您确定状态”(deleteCounter === 1
)上,但是在删除后,它进入了初始状态(deleteCounter === 0
)。似乎第3个组件状态尚未更新其deleteCounter
,但是其数据(玩家的名称仍已更新)。
在成功删除<Games>
组件数据后,再次获取。
答案 0 :(得分:2)
您不需要删除计数器即可实现此目的。相反,这使您难以理解您的代码。只需使用这样的布尔值即可:
<template>
<div>
<button @click="clickButton"
<template v-if="confirmation">
<i class="trash icon"></i>
</template>
<template v-else>
Are you sure?
</template>
</button>
<button v-if="confirmation" @click="confirmation = false">
<i class="undo icon"></i>
</button>
</div>
</template>
<script>
export default {
name: 'DeleteWithConfirmation',
data() {
return {
confirmation: false
}
},
methods: {
clickButton() {
if (!this.confirmation) {
this.confirmation = true;
} else {
this.$emit('deleting-confirmed');
}
}
}
</script>
然后,父母可能正在寻找像这样:
<div class="row" v-if="showButton">
[...]
<delete-with-confirmation @deleting-confirmed="showButton = false">
</div>
答案 1 :(得分:2)
其中一个答案已删除,希望我能提及最初的作者,但我不保留他的用户名,所以(稍作改动):
incrementDelete() {
if (this.deleteCounter === 1) { // 1 because there is "post-increment" at the end of the fucntion
this.deletingProgress = true
this.$emit('deletingConfirmed')
this.stopDeleting()
}
else if (this.deleteCounter > 1) // 1 because there is "post-increment" at the end of the fucntion
this.stopDeleting()
this.deleteCounter++ // "post-increment"
},