如何在渲染Vue组件时触发事件?

问题描述:

我google了很多,但没有发现任何关于此。如何在渲染Vue组件时触发事件?

我想在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 & 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') 
    } 
}); 

有谁知道我的问题很好的解决方案?

谢谢。

+0

您使用的是哪个版本的Vue?可以在VueJS 2中以编程方式处理转换,并且您希望使用挂载的钩子而不是'created'钩子,因为到那时它将被应用到DOM。 –

+0

@DavidL,似乎将'created'更改为'mounted'没有帮助。我正在使用Vue的最新版本。好的,谢谢,我现在尝试使用转换。 – terron

+0

如果可能的话,我肯定会推荐vue通过钩子的外部解决方案进行转换。 –

非常感谢@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的工作结果。