如何在呈现Vue组件时触发事件?

时间:2016-11-15 20:15:50

标签: javascript vue.js vue-component

我已经搜索了很多,但没有发现任何相关信息。

我希望在Vue渲染时淡出我的内容。我的应用程序很大,需要一些时间为用户做好准备。但是当Vue将内容插入块时,CSS动画不希望工作。请参阅以下JSFiddle列出的代码。

HTML

<div id="my-app">
    <p>Weeverfish round whitefish bass tarpon lighthousefish mullet tigerperch bangus knifefish coley Black sea bass tompot blenny madtom tapetail yellow-eye mullet..</p>

    <hr>

    <example></example>
</div>

CSS

#my-app {
    opacity: 0;
    transition: 2s;
}

#my-app.visible {
    opacity: 1;
    transition: 2s;
}

的JavaScript

// Fade in animation will work if you comment this ...
Vue.component('example', {
    template: `<p>Starry flounder loach catfish burma danio, three-toothed puffer hake skilfish spookfish New Zealand sand diver. Smooth dogfish longnose dace herring smelt goldfish zebra bullhead shark pipefish cow shark.</p>`
});

// ... and this 
const app = new Vue({
    el: '#my-app',

    // Makes content visible, but don't provides fade-in animation
    /*
    created: function () {
        $('#my-app').addClass('visible')
    }
    */
});

// Makes content visible, but don't provides fade-in animation
// with enabled Vue
$('#my-app').addClass('visible');

// As you can see, animation with Vue works only here
setInterval(() => {
    $('#my-app').toggleClass('visible');
}, 5000);

此外,在渲染Vue时,我没有找到任何内置的Vue解决方案(事件,方法等)来运行代码。像load&amp; DOMContentLoaded也没有帮助。 created也未提供预期结果:

const app = new Vue({
    el: '#my-app',
    // Makes content visible, but don't provides fade-in animation
    created: function () {
        $('#my-app').addClass('visible')
    }
});

有没有人知道我的问题的好方法?

感谢。

1 个答案:

答案 0 :(得分:1)

非常感谢@David L@Bill Criswell指向Transition Effects。我用这段代码达到了预期的结果:

<强> HTML

<div id="my-app">
    <app>
        <p>Weeverfish round whitefish bass tarpon lighthousefish mullet tigerperch bangus knifefish coley Black sea bass tompot blenny madtom tapetail yellow-eye mullet..</p>

        <hr>

        <example></example>
    </app>
</div>

<强> CSS

.fade-enter-active, .fade-leave-active {
    transition: opacity 1s
}

.fade-enter, .fade-leave-active {
   opacity: 0
}

<强>的JavaScript

Vue.component('app', {
    data: function () {
        return {
            show: false
        }
    },
    mounted: function() {
        this.show = true;
    },
    template: `<div>
        <transition name="fade">
            <div v-if="show">
                <slot></slot>
            </div>
        </transition>
    </div>`,
});

Vue.component('example', {
    template: `<p>Starry flounder loach catfish burma danio, three-toothed puffer hake skilfish spookfish New Zealand sand diver. Smooth dogfish longnose dace herring smelt goldfish zebra bullhead shark pipefish cow shark.</p>`
});

const app = new Vue({
    el: '#my-app',
});

以下是JSFiddle的工作结果。

相关问题