javascript - CSS 动画仅在首次创建时触发

标签 javascript css vue.js css-animations vuejs2

这是我使用 Vuejs 的第一个元素。

我已经有了我的主要组件。在我的主要组件中,我有一个数据变量,它是一个数组。例如:

export default {
    name: 'example-component',
    data() {
        return {
            options: [
                {
                    text: {
                        nl: 'Jan',
                        en: 'John',
                    },
                    action: 'x1',
                },{
                    text: {
                        nl: 'Jansen',
                        en: 'Doe',
                    },
                    action: 'x2',
                },
            ],
        }
    },
}

在我的模板中 <example-component>我在另一个组件内使用 v-for 循环。如下图所示:

<my-other-component v-for="option in options" v-on:click.native="select(option.action)"
    :key="option.id"></my-other-component>

这似乎工作正常。

<my-other-component>当它第一次出现在屏幕上时有一个动画。

methods我的部分example-component有一种方法有时会清空 options数组并重新填充它,当然,用不同的对象。如果现在运行此方法,前两个选项将没有有此动画,但第三个、第四个、第五个等等会有。

所以看起来这个动画会在 options 中首次创建特定索引时触发。数组。

有谁知道这是为什么以及如何解决这个问题?

PS:我的(相关)CSS:

.option {
    animation-timing-function: linear;
    animation-name: option;
    animation-duration: 2.5s;
}

@-webkit-keyframes option{
    0% { opacity: 0; }
    75% { opacity: 0; }
    100% { opacity: 1; }
}

-

编辑1:

添加animation-iteration-count: infinite并不能解决问题。它只是重复动画。 (->“选项”每 2.5 秒消失并重新出现)

编辑2:

我试着摆弄了一下。这似乎与时机有关。如果删除操作选项和再次添加它们之间有足够时间,动画似乎工作正常。

另外,我尝试了不同的方法来清空我的数组,IE:

this.options = [];
this.options.length = 0;
this.options.splice(0, this.options.length);
// And all the other goodness

但它们似乎都不影响这个问题。

最佳答案

https://v2.vuejs.org/v2/guide/list.html#Components-and-v-for

In 2.2.0+, when using v-for with a component, a key is now required.

When Vue is updating a list of elements rendered with v-for, it by default uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will simply patch each element in-place and make sure it reflects what should be rendered at that particular index.

To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item. An ideal value for key would be the unique id of each item.

基本上,如果您没有为循环中的每个数据对象提供唯一的 ID 并将其绑定(bind)到正在循环的元素,Vue 将在数据更改时简单地“修补”数据,并且不会触及 DOM。

关于javascript - CSS 动画仅在首次创建时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45309059/

相关文章:

javascript - 如何在简短的 if 语句中编写 else if ?

javascript - AngularJS 与 RequireJS 路由删除哈希

html - Bootstrap slider 宽度父级(12 个断点)

html - 如何按特定顺序将 3 个元素并排 float ?

vue.js - Axios 拦截器配置 - URL 不一样

vue.js - 循环出输入属性?

javascript - 无法从 &lt;input&gt; 获取值

java - 解码 javascript 编码的 url

javascript - vue/vuetify 中的 {on, attrs} 有何作用?

javascript - 在点击功能上动画化图像,同时重叠其兄弟元素