在删除数组项之前添加css动画

时间:2018-04-29 20:00:51

标签: javascript vue.js

在从数据表中删除项目之前,我想做一个css动画。删除元素由事件@click触发。所以我想首先看看我的动画做什么(类delete_animation)并且只在删除元素之后才能看到。



var vm = new Vue({
  el: '#app',
  data: {
  	addedId: null,
		array: [
    	{ id: 1, text: "lorem ipsum" },
      { id: 2, text: "lorem ipsum" },
    ]
  },
  methods: {
  	add() {
    	this.addedId = this.array[this.array.length - 1].id + 1;
      this.array.push({ id: this.addedId, text: "lorem ipsum"} );
    },
    remove(item, index) {
      this.array.splice(index, 1);
      this.addedId = null;
      // ???
    }
  }
});

table {
    border-collapse: collapse;
}

table, th, td {
    border: 1px solid black;
}

.add_animation {
  animation: addItem 1s;
}

@keyframes addItem {
  0% {
    background-color: green;
  }
  100% {
    background-color: white;
  }
}
.deleted_animation {
  animation: deleteItem 1s;
}
@keyframes deleteItem {
  0% {
    background-color: red;
  }
  100% {
    background-color: white;
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>
<div id="app">
  <table>
    <tr v-for="(index, item) in array" :key="item.id" :class="addedId == item.id ? 'add_animation' : ''">
      <td>{{ item.text }}</td>
      <td> <button type="button" @click="remove(item, index)">remove</button></td>
    </tr>
  </table>
  <button type="button" @click="add()">Add</button>
</div>
&#13;
&#13;
&#13;

我只想做与#34;添加&#34;相反的事情。按钮呢。但是,我没有看到如何处理等待动画显示的事件。我想我需要在显示动画后触发点击,但我不知道如何......

谢谢!

3 个答案:

答案 0 :(得分:2)

我不确定,但据我所知,你想使用vue.js动画删除数组中的项目。

vue.js的一切都很简单,请参阅Vue.js Transitions

我为你做了一个简单的例子,当你删除它们时为它们制作动画。它可以帮助你。

See it in action here

“html”部分

<div id="app">
  <transition-group name="fade">
      <div v-for="(todo,index) in todos" :key="todo.text" @click="deleteItem(index)">
        {{ todo.text}}
      </div>
  </transition-group>
</div>

javascript部分

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true }
    ]
  },
  methods: {
        deleteItem(index) {
        this.todos.splice(index, 1);
    }
  }
})

css部分

.fade-leave-active {
  transition: all 1s;
}

.fade-leave-to {
  opacity: 0;
}

答案 1 :(得分:1)

在列表周围添加<transition-group>元素,并将转换写为CSS转换,Vue.js将负责设置正确的CSS类,在退出转换运行时保持元素存在。无需改变你的逻辑。有关确切的详细信息,请查看&#34;列表转换&#34;文档部分。

https://vuejs.org/v2/guide/transitions.html#List-Transitions

答案 2 :(得分:0)

如果首先将deletedItem类添加到单击的项目中:

document.querySelectorAll('tr')[index].classList.add('deleted_animation')

(我相信您可以找到更好的方法来选择点击的项目)

然后使用setTimeout延迟操作:

setTimeout(() => {
    this.array.splice(index, 1);
    this.addedId = null;
}, 500)

你将实现大部分目标。由于您可能会多次快速单击“删除”按钮,因此根据索引不会很好。因此,可能在单击按钮后,您可以阻止所有按钮上的单击操作,然后在拼接项目后将其添加回来。